Const vs Static vs Readonly in C#

CsharpProgrammingServer Side Programming

Const

Constant fields are the fields that cannot be modified. At the time of declaration, you need to assign a value to it.

const int a = 5;

Static

If the static modifier is applied to a class then you cannot instantiate the class using the new keyword. You can use the static keyword on methods, properties, classes, constructors, etc.

static int a = 10;

Readonly

A Readonly field is initialized at the time of declaration or you can also set it within the constructor.

Let us see an example in which the readonly field is initialized inside the constructor.

Example

class Demo {
   readonly int a;
   public Demo( ) {
      a = 5;
   }
}
raja
Published on 17-Sep-2018 16:43:18
Advertisements