Const Vs Read-only Keywords in C#

Let's get started.

Const:

  1. We can declare a variable as a constant using the const keyword in C#.

  2. 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.

  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.

Read-only:

  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 assigned 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 a 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 blog, 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 blog.

Next Recommended Reading Object VS Dynamic VS Var in C#