Tutorialsteacher

Follow Us

Difference between Static, Readonly, and Constant in C#

The following table lists the difference between Static, Readonly, and constant in C#.

staticreadonlyconst
Declared using the static keyword.Declared using the readonly keyword.Declred using the const keyword. By default a const is static that cannot be changed.
Classes, constructors, methods, variables, properties, event and operators can be static. The struct, indexers, enum, destructors, or finalizers cannot be static.Only the class level fields can be readonly. The local variables of methods cannot be readonly.Only the class level fields or variables can be constant.
Static members can only be accessed within the static methods. The non-static methods cannot access static members.Readonly fields can be initialized at declaration or in the constructor.

Therefore, readonly variables are used for the run-time constants.
The constant fields must be initialized at the time of declaration.

Therefore, const variables are used for compile-time constants.
Value of the static members can be modified using ClassName.StaticMemberName.Readonly variable cannot be modified at run-time. It can only be initialized or changed in the constructor.Constant variables cannot be modified after declaration.
Static members can be accessed using ClassName.StaticMemberName, but cannot be accessed using object.Readonly members can be accessed using object, but not ClassName.ReadOnlyVariableName.Const members can be accessed using ClassName.ConstVariableName, but cannot be accessed using object.

The following example demonstrates the difference between static, readonly, and const variables.

Example: static vs readonly vs const
public class Program
{
	public static void Main()
	{
		MyClass mc = new MyClass(50);
		mc.ChangeVal(45);
		mc.Display();
		
		Console.WriteLine("MyClass.constvar = {0}", MyClass.constvar);
		Console.WriteLine("MyClass.staticvar = {0}", MyClass.staticvar);
	}
}

public class MyClass
{
	public readonly int readonlyvar1 = 10, readonlyvar2;
	public const int constvar = 20;
	public static int staticvar = 0;
	public MyClass(int i)
	{
		readonlyvar2 = i; // valid
		//z = i; //compile-time error
		staticvar = i; // valid
	}

	public void ChangeVal(int val)
	{
		//x = val;
		//z = i; //compile-time error
		staticvar = val; // valid
	}

	public void Display()
	{
		Console.WriteLine(staticvar);
		Console.WriteLine(readonlyvar1);
		Console.WriteLine(constvar);
	}
}