X

C# readonly what is that for?

dotnet C#

C# readonly what is that for? The readonly keyword in C# is used as a modifier. A field can be declared with readonly modifier, and its assignment can only be in the Constructor or when the variable is declared.

An example:


public readonly int MinAge = 10; //this is valid

public class Person
{
  public readonly int _age;
  public Person(int age)
  {
    _age = age; //this is also valid
  }

  public void SetAge(int age)
  {
    _age = age; //this is invalid, one cannot set it here would give compile error
  }

  public int Age 
  {
    get { return _age; }  //this is also valid no setter just getter
  }
}

The main thing to understand about readonly modifiers is that they are initialized at runtime, not like const where they initialized at compile time.

One advantage of using readonly is that you do not need to recompile external Dll that may use the value of it, but const would require a replaced of all the dll that are using the value.

The other advantage is to create immutable data structures in your program such they cannot be changed once constructed.

Categories: .NET C#
Taswar Bhatti:
Related Post