About
In this code snippet, we will take a look at the readonly keyword in C#.
Obviously, a variable/field marked as readonly can not be modified after it was set. However, readonly can be set at run time in the constructor or when it’s declared(at compile time) unlike const which can only be set at compile time.
Let’s have a look at the code below to see how to use readonly.
Code:
var myClass = new MyClass(); Console.WriteLine(myClass.MyProperty); Console.WriteLine(myClass.MySecondProperty); //Console.WriteLine(myClass.Pi); //This will not compile as consts are also static. Console.WriteLine(MyClass.Pi); Console.ReadLine(); class MyClass { //Readonly fields can be set when declared(at compile time) or ... public readonly int MyProperty = 10; //at run time in the constructor like MySecondProperty. public readonly int MySecondProperty; //A constatnt can only be set when declared(at compile time). public const float Pi = 3.14f; public MyClass() { //Pi = 5; //This will not compile. MySecondProperty = 15; } }