Difference between Constant, read-only and static in C#

In this blog, we will learn about constant, read-only and static keywords in C# programming.

We use const and readonly keyword to make a field constant and which values we can not modify.

Const keyword

We can not modify the value of a field if it is const.

Let’s consider the code:

int val = 1;
public void Print()
{
    val = val + 1;
}

This code works fine with no errors.

Now, we declare a variable with the const keyword. Consider this code snippet:

const int val = 1;
public void Print()
{
    val = val + 1;
}

This code will not work as we are not supposed to modify the value of a const member.

So, we should not create a constant field if we expect to change its value at a later stage.

This is an invalid code snippet:

 public static const int val = 1; // The constant 'val' cannot be marked static

Key facts about Constant

  • Constant may not be modified after declaration.
  • We must assign a value at the time of declaration.
  • We can not mark a constant as static and vice-versa.

Read Only keyword


A readonly field can be initialized either at the time of declaration or within the constructor of the same class. Therefore, read-only fields can be used for run-time constants.

Static
The static keyword is used to specify a static member, which means static members are common to all the objects and they do not tied to a specific object. This keyword can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes.

Summary:

1. Constants are known at compile time, Read-only variables are known at run time.
2. Constants can be assigned values only at the time of declaration, Read-only variables can be assigned values either at runtime or at the time of instance initialization via the constructor

Leave a Comment

RSS
YouTube
YouTube
Instagram