Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Readonly keyword in C#

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 219
    Comment on it

    Readonly keyword


    Readonly: Readonly is a keyword which when used with a variable then the value of that variable can only be changed either at runtime or at the time of the instance initialization. The value is assigned to these variable when they are declared or in the constructor of the class i.e reassignment is only possible through constructor of the class otherwise value of readonly variable cannot be changed. Readonly keyword cannot be used with variables in the methods even the value of readonly variable cannot be changed in any method of the class. 

    Program to demonstrate readonly keyword:
     

    public class ReadOnlyTest
    {
       class SampleClass
       {
          public int x;    //variable without readonly
          public readonly int y = 25;   //readonly variabble
          public readonly int z;       //readonly variabble
    
          public SampleClass()
          {
             // Initialize a readonly instance field
             z = 24;
          }
    
          public SampleClass(int p1, int p2, int p3)
          {
           //Readonly variable can be changed via constructor
             x = p1;
             y = p2;
             z = p3;
          }
       }
    
       static void Main()
       {
          //readonly variable are changed via constructor
          SampleClass p1 = new SampleClass(11, 21, 32);
          Console.WriteLine("p1: x={0}, y={1}, z={2}", p1.x, p1.y, p1.z);
          SampleClass p2 = new SampleClass();
          //variable without readonly can be changed but p2.y=10 will give error as it is readonly 
          p2.x = 55;  
          Console.WriteLine("p2: x={0}, y={1}, z={2}", p2.x, p2.y, p2.z);
       }
    }
    

    Output:

     p1: x=11, y=21, z=32
     p2: x=55, y=25, z=24

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: