What are the benefits to marking a field as readonly in C#?


The readonly keyword is used to declare a member variable a constant, but allows the value to be calculated at runtime. This differs from a constant declared with the const modifier, which must have its value set at compile time. Using readonly you can set the value of the field either in the declaration, or in the constructor of the object that the field is a member of.

The 'readonly' modifier can be used in a total of four contexts:

  • Field declaration

  • Readonly struct declaration

  • Readonly member definition

  • Ref read only method return

When we use the field declaration context, we need to know that the only time the assignment can occur is when it is declared or when the constructor of the same class is invoked.

Example

class Program{
   readonly string Name;
   public Program(){
      Name = "Name";
   }
   static void Main(string[] args){
      Program a = new Program();
      System.Console.WriteLine(a.Name);
      Console.ReadLine();
   }
}

Output

Name

readOnly Struct

public readonly struct Server{
   public readonly string Name;
   public Server(string name){
      Name = name;
   }
}
class Program{
   static void Main(string[] args){
      Server a = new Server("Domain Controller");
      System.Console.WriteLine(a.Name);
      Console.ReadLine();
   }
}

Output

Domain Controller

Updated on: 07-Nov-2020

356 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements