Constants VS ReadOnly

Constants are similar to read-only fields. You can’t change a constant value once it’s assigned. The const keyword precedes the field to define it as a constant. Assigning value to a constant would give a compilation error. For example:

const int num3 = 34;
num3 = 54;

// Compilation error: the left-hand side of an assignment must 
// be a variable, property or indexer

Although constant are similar to read-only fields, some differences exist. Constants are always static, even though you don’t use the static keyword explicitly, so they’re shared by all instances of the class.

The readonly keyword differs 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. Therefore, readonly fields can have different values depending on the constructor used.

Example Constant

public class ConstTest 
{
    class SampleClass
    {
        public int x;
        public int y;
        public const int c1 = 5;
        public const int c2 = c1 + 5;

        public SampleClass(int p1, int p2)
        {
            x = p1;
            y = p2;
        }
    }

    static void Main()
    {
        SampleClass mC = new SampleClass(11, 22); 
        Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
        Console.WriteLine("c1 = {0}, c2 = {1}",
                          SampleClass.c1, SampleClass.c2 );
    }
}

Example ReadOnly

    public class ReadOnlyTest
    {
       class SampleClass
       {
          public int x;
          // Initialize a readonly field
          public readonly int y = 25;
          public readonly int z;

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

          public SampleClass(int p1, int p2, int p3)
          {
             x = p1;
             y = p2;
             z = p3;
          }
       }

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



By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

Popular posts from this blog

Example to disable save as certain file type in SSRS Report Viewer

Phone book application example - Java

Modal Popup Message Box ASP.NEt C# Example