Search This Blog

Friday, January 29, 2016

Difference between Readonly and Const in C# with example

Difference between Readonly and Const in C# with example
Constant

Constant fields are defined at the time of declaration in the code snippet, because once they are defined they can't be modified. By default a constant is static, so you can't define them static from your side.

It is also mandatory to assign a value to them at the time of declaration otherwise it will give an error during compilation of the program snippet. That's why it is also called a compile-time constant.
Readonly

A Readonly field can be initialized either at the time of declaration or within the constructor of the same class. We can also change the value of a Readonly at runtime or assign a value to it at runtime (but in a non-static constructor only).

For that reason a Readonly field is also called a run-time constant.

public class ReadOnlyConstDynamicVar
    {
        public const int x = 10; // assigning value is mandatory
        public readonly int y ; // assigning value is optional

        public ReadOnlyConstDynamicVar()
        {
            //readonly takes default value if nothing is assigned
            y = 20;
        }

        public string GetreadOnlyValue()
        {           
            //y = 20;  // not allowed to change readonly variable
            const int g = 30;
            return g.ToString();
        }
    }

       static void Main(string[] args)
        {           
            ReadOnlyConstDynamicVar obj = new ReadOnlyConstDynamicVar();
            //reading const value
            Console.WriteLine(ReadOnlyConstDynamicVar.x.ToString());
            //reading readonly value
            Console.WriteLine(obj.y.ToString());

            Console.ReadLine();
        }


Post a Comment

Popular Posts