const vs readoly vs static

Constant and ReadOnly (const and readonly) variables in C# make a variable whose value cannot be changed. The static keyword is used to create a static variable that shares a value for all instances of that class. In this article we will learn about the differences between them.

Constant

Constant fields or constant variables must be assigned a value at the time of declaration, then their value cannot be changed. By default, constant is static, so you cannot declare the static keyword for the constant variable.

public const int X = 10;

A constant variable is a compile-time constant. A constant variable can be initialized by an expression but must ensure that the operands in the expression must also be constants.

void Calculate(int Z)
{
 const int X = 10, X1 = 50;
 const int Y = X + X1; //no error, since its evaluated a compile time
 const int Y1 = X + Z; //gives error, since its evaluated at run time
}

You can apply the const keyword to primitive types (byte, short, int, long, char, float, double, decimal, bool), enum, a string, or a reference type that can be assigned a value. null.

const MyClass obj1 = null;//No error
const MyClass obj2 = new MyClass();//Error when runtime

Constant variables can be assigned all access modifiers such as public, private, protected, internal. You use constant variables in cases where you are sure their value will not change.

ReadOnly

A Readonly variable can be initialized at declaration time or in the class's constructor. So readonly variables can be used as run-time constants.

class MyClass
{
 readonly int X = 10; // Initialized at declaration
 readonly int X1;

 public MyClass(int x1)
 {
 X1 = x1; // initialized at runtime
 }
}

Readonly can be applied to both value and reference types except delegates and events. Use readonly when you want to create constant variables at runtime.

Static

The static keyword is used to make a variable or member static, meaning its value will be shared by all objects and not attached to any particular object. The static keyword can be applied to classes, fields, properties, operators, events, and constructors, but cannot be used for indexes, destructors, or anything other than classes.

class MyClass
{
 static int X = 10;
 int Y = 20;
 public static void Show()
 {
 Console.WriteLine(X);
 Console.WriteLine(Y); //The error is because static methods can only access static variables
 }
}

Knowledge of static keyword

  • If the static keyword is applied to a class, all elements in the class must also be static

  • Static methods can only access other static elements in the class. Static properties are used to set and get values ​​for the values ​​of static variables in the class.

Static constructors cannot have parameters. Access modifiers cannot be applied to static constructors, there is always a public default constructor to initialize static variables for clas

Last updated