What is difference between readonly and const in C#?

Answer: Use and conceptual difference between readonly and const in C# with example.

CONST: The constant -const variable cannot be changed once it has been declared and initialized. If we try to change it anywhere in the class, compiler will flash an error at compile time.

Generally, at the time of class design we decide, what field to make const, so, it cannot be changed accidently during writing of class functions.

For example, in a class we may want to have PI =3.14, as a const variable to calculate the area of a circle, as it is not supposed to be changed anywhere in any methods.

READONLY: Also, readonly variable cannot be changed anywhere in the class accept class constructor or initializer list( where class fields are declared). If we try to change readonly variable anywhere in the functions of the class, it will flash an error at compile time itself.

Some time we may want to initialized some variable during object creation and don’t want it to be changed anywhere in the class, then, we have to make it readonly.

Example with comments:

class Circle
{
    private const double PI = 3.14; // const value
    // public readonly int radious =10; // OK //Read only, can be intialized here.
    public readonly int radious;

    public Circle(int radious)// Constructor
    {
        //Readonly variable can be assigned
        //in constrctor only and not in any functions.
        this.radious = radious;
    }

    public double GetArea()
    {

        //this.radious = 10;// Not OK and compiler error.  
        return PI * radious * radious;
    }

}

class Program
{
    static void Main(string[] args)
    {

        Circle c = new Circle(5);

        Console.WriteLine("Area of Circle :" + c.GetArea());

    }
}

Related Posts