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.
- public const int firstnumber = 10;
- const int x = 10;
- const int y = 20;
- const int z = x + y;
- Console.WriteLine("The value of x :" + x);
- Console.WriteLine("The value of y :" + y);
- Console.WriteLine("The value of z :" + z);
- int a = 15;
- const int b = x + a;
- Console.WriteLine("The value of b :" + b);
- //The variable 'a' is assigned but its value is never used
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.
- public class MyClassProgram
- {
- readonly int x = 10;
- public MyClassProgram()
- {
- //changed the value in constructor
- x = 20;
- }
- }
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.
- public static class ReadOnly
- {
- static int number = 10;
- public static void disp()
- {
- Console.WriteLine(number);
- }
- }
- Constant is compile time constant and it is by default static.
- ReadOnly is run time constant and you can define it static explicitly.
- 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#.


Santhakumar MunuswamyPosted Oct 18, 2015, 2:01 AM EDT
Good one
Mukesh KumarPosted Oct 16, 2015, 1:47 AM EDT
Thanks Suman
Suman VermaPosted Oct 16, 2015, 1:43 AM EDT
Nice article
Mukesh KumarPosted Oct 11, 2015, 1:50 AM EDT
Thanks shibuthomas
shibuthomas mathaiPosted Oct 11, 2015, 1:30 AM EDT
Thanks.It really helped me
Mukesh KumarPosted Oct 6, 2015, 9:33 PM EDT
thanks
Ankit BansalPosted Oct 6, 2015, 9:29 PM EDT
nice..thanks for sharing knowledge..
Mukesh KumarPosted Oct 6, 2015, 9:20 AM EDT
Thanks sir
Priyaranjan K STOP 100Posted Oct 6, 2015, 9:09 AM EDT
Good One ..
Mukesh KumarPosted Oct 6, 2015, 6:59 AM EDT
Thanks for your supports
Gowtham KTOP 100Posted Oct 6, 2015, 6:58 AM EDT
Thanks for sharing
Mukesh KumarPosted Oct 6, 2015, 5:31 AM EDT
Thanks
Nilesh JadavPosted Oct 6, 2015, 5:20 AM EDT
Nice one sir !