R4R
Right Place For Right Person TM
 

R4R C# C# Examples Define Readonly in C#

C# Examples             

Index 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

Example of Readonly keyword in C#

         



/*readonly
The readonly keyword is different from the const keyword.
 A const field can only be 
initialized at the declaration of the field. A readonly 
field can be initialized either at the
 declaration or in a constructor.
*/
using System;
public class ReadOnlyTest 
{
   class MyClass 
   {
      public int x;
      public readonly int y = 25; // Initialize a readonly field
      public readonly int z;

      public MyClass() 
      {
         z = 24;   // Initialize a readonly instance field
      }

      public MyClass(int p1, int p2, int p3) 
      {
         x = p1; 
         y = p2; 
         z = p3;
      }
   }
   public static void Main() 
   {
      MyClass p1= new MyClass(11, 21, 32);   // OK
      Console.WriteLine("p1: x={0}, y={1}, z={2}" , p1.x, p1.y, p1.z);   
      MyClass p2 = new MyClass();
      p2.x = 55;   // OK
      Console.WriteLine("p2: x={0}, y={1}, z={2}" , p2.x, p2.y, p2.z);
   }
}

 Download Source Code

Index 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

New Updates

R4R
R4R
R4R
R4R
R4R
R4R
R4R
R4R