Constant and ReadOnly in C# create a variable that can't be changed. The static keyword is used to create static variables that share values for all instances of that class. In this article we will learn about the differences between them.
Constant
Constant variable must be assigned a value at declaration and they cannot be changed. By default constant is static, it is not possible to declare a static keyword for a constant variable.
public const int a = 5;
A constant variable is a constant from compilation. A constant variable can be initialized by an expression but must ensure that the operands in the expression must also be constant.
void Calculate(int a)
{
const int x = 10, b = 50;
const int Y = x + b; //no error, since its evaluated a compile time
const int z = x + a; //gives error, since its evaluated at run time
}
You can apply the const keywords to primitive types (bytes, short, int, long, char, float, double, decimal, bool), enum, a string, or a reference type and can assign values null.
const MyClass c1 = null; //no error
const MyClass c2 = new MyClass(); //error
The constant variable can be assigned to all access modifiers such as public, private, protected, internal. You use constant variables in case their values are not changed.
ReadOnly
A Readonly variable can be initialized at the time of declaration or in the constructor of that class. So readonly variables can be used as constants at execution.
class MyClass
{
readonly int a = 10;
readonly int b;
public MyClass(int c)
{
b = c; // initialize at run time
}
}
Readonly can be applied to both value type and reference type except delegate and event. Use readonly when you want to create constant variables at run time.
Static
The static keyword is used to create a variable or a static element, meaning that its value will be shared for all objects and not attached to any particular object. Static keywords can be applied to both class, fields, properties, operators, events, constructors but cannot be used for indexes, destructors, or any other type of classes.
class MyClass
{
static int a = 5;
int b = 7;
public static void Show()
{
Console.WriteLine(a);
Console.WriteLine(b); //error because static method only access static variable
}
}
If the static keyword is applied to a class, all the components in the class must be static.
Static methods can only access other static components in the class. The static properties are used to set and get values for the values of static variables in the class.
Static constructor cannot have parameters. Can't apply access modifiers to static constructor, always have a default constructor public to initialize static variables for class.