Search This Blog

Monday, July 8, 2019

Difference Between Const, ReadOnly and Static ReadOnly in C#

const:

            A variable of which value is constant but at compile time it is manadatory to assign the value
           can  not change Throughout the entire program
  class ConstField
    {
        const int Id = 0;
        const int Id; //Compile Time Error
        public ConstField()
        {
            Id = 1; // Compile Time Error
        }
        public Test()
        {
            Id = 1; // Compile Time Error
        }
    }

readonly :

                  readonly is the Keyword whose value we can change during runtime but only through non  static class

  class ReadOnlyField
    {
        readonly string lName;
        static ReadOnlyField()
        {
            lName = "Assign Value"; // Compile time error
        }
        public  ReadOnlyField()
        {
            lName = "Assign Value"; // Compile time error
        }

    }

static readonly :

A Static Readonly type variable's value can be assigned at runtime or assigned at compile time and changed at runtime. But this variable's value can only be changed in the static constructor. And cannot be changed further. It can change only once at runtime

  static  readonly string lName ;
        static  ReadOnlyField()
        {
            lName = "Assign Value"; // Compile time error
            Console.WriteLine(lName);

        }


  static  readonly string lName ;
        static  ReadOnlyField()
        {
            lName = "Assign Value"; // Compile time error
            Console.WriteLine(lName);
        }

Static :



When we don’t want to create multiple instance of a variable, i.e., we want to access the same value across multiple instance of class, then we can opt for a static variable.

No comments :