Constant, ReadOnly And Static Keyword In C#

Constant

Constant means as you know in mathematics “which can’t be changed after declaration". You can declare a value type as well as reference type data type [only which can assign null] as Constant. It can be an object of reference type or field or local variable but value never change if you define once. By default constant are static, so you cannot define a constant type as static.

  1. public const int firstnumber = 10;  
It is a compile-time constant. A field or local variable which is declared as constant can be initialized with a constant expression which must be fully evaluated at compile time.
  1. const int x = 10;  
  2. const int y = 20;  
  3. const int z = x + y;  
  4. Console.WriteLine("The value of x :" + x);  
  5. Console.WriteLine("The value of y :" + y);  
  6. Console.WriteLine("The value of z :" + z);   
  7.   
  8. int a = 15;  
  9. const int b = x + a;  
  10. Console.WriteLine("The value of b :" + b);  
  11. //The variable 'a' is assigned but its value is never used  
You can mark Constants as public, private, protected, internal, or protected internal access modifiers.

When to use

If you think that the value of field or local variable is never changed.

ReadOnly

It is same as Constant but it is run time constant. I mean to say that a ReadOnly field or local variable can be initialized either at the time of declaration or inside the constructor of same class. That is why we called it run time constant.
  1. public class MyClassProgram  
  2. {  
  3.    readonly int x = 10;  
  4.    public MyClassProgram()  
  5.    {  
  6.       //changed the value in constructor  
  7.       x = 20;  
  8.    }  
  9. }  
As you know that we cannot declare Constant as static but we can do it for readonly explicitly. By default it is not static. It can be applied to value type and reference type [which initialized by using the new keyword)] both and also with delegate and event

When to use

If you think, you need to change the value of variable or field at run time inside the calling constructor, then you need to use the readonly modifier.

Static

Static keyword is a special keyword. It can be used with class member, methods, fields, properties, events, constructors as well as with class. It is used to specify a static member which is common for the entire object.
  1. public static class ReadOnly  
  2. {  
  3.    static int number = 10;  
  4.    public static void disp()  
  5.    {  
  6.       Console.WriteLine(number);  
  7.    }  
  8. }  
Key Points about all these three:

 

  1. Constant is compile time constant and it is by default static.
  2. ReadOnly is run time constant and you can define it static explicitly.
  3. Static does not work with indexers and if you create a class as static as you need to create all class members as static.

So, finally you learn what is Constant, ReadOnly and Static keyword in C#.


Similar Articles