Author : MD TAREQ HASSAN | Updated : 2021/03/22


Readonly variable can be assigned only once (declaration time, in constructor or in static constructor)

public readonly int y = 5;

class Foo
    readonly int bar;
    Foo(int bar)
    { = bar;

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 assigned multiple times in the field declaration and in any constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants as in the following example:

public static readonly uint timeStamp = (uint)DateTime.Now.Ticks;

See: readonly (C# Reference)


static class Constants
    public const double Pi = 3.14159; // no need to use static keyword
var area = Constants.Pi * (radius * radius);