Const vs. Readonly Keywords in C#

C#

5.00 ( 1 votes) | 1388

In this article, we will talk about two most commonly used keywords “const” and “readonly” and the difference between them. Let`s get started.

Const:

  1. We need to assign a value to constant variable at the time of declaration by using a hard coded value or an expression which can be fully evaluated at compile time.
  2. We can declare a variable as a constant using the const keyword in C#. 
  3. Only built in data types like int, string, boolean etc can be marked as constant variable.
  4. Once the value is assign to constant variable at the time of declaration, then we can`t change its value. It we try to change the value then we will get compilation error “The left-hand side of an assignment must be a variable, property or indexer”. Because of which constant variables are most commonly called as Compile time constant.
  5. Compiler compiles the constant value to every location that references it. For example, initially we declare a constant variable with value X and we are using that variable in method named as foo(). After that we change the value to Y then we need to compile the code again so that the change will get reflected in method foo().
  6. Constant variable are static. So we can access constant variable using the class name.
  7. Best practice for naming the constant variable is to use Pascal casing.

Readonly:

  1. We can declare a variable as a read-only variable using the readonly keyword in C#.
  2. We can assign a value to read-only variable at the time of declaration or in constructor. Once the value is assign then we can`t change it.
  3. As we can assign a value to read-only variable using constructor, it can have different value for different constructor. Because of which read-only variables are most commonly called as Run Time Constant.
  4. We can use any data type as a read-only variable.
  5. We can use static keyword with read-only variables.
  6. Best practice for naming the read-only variable is to use Pascal casing.

When to use constant and when to use read-only variable:

So the main Key points are:

  1. If we know that the value of the variable is not going to change in any part of our application then we can declare that variable as a constant variable. For example PI=3.14.
  2. If we are unsure about the value of variable, but we don`t want other classes to change the value then, we can declare that variable as read-only.

Conclusion:

In this article, we talked about the difference between constant and read-only variables in C# and when should we use them. I hope you enjoyed reading the article.

Happy Coding!!!

Manoj Kulkarni - Dotnetcontext

Manoj Kulkarni

I am programmer, passionate blogger and foodie. I live in Nashik. I am a .Net developer. I like to learn new technologies to keep my self-updated and share that knowledge with my blog readers, friends and colleague.

Add a new comment