Let's get started.
- We can declare a variable as a constant using the const keyword in C#.
- 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.
- Only built in data types like int, string, boolean etc can be marked as constant variable.
- 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.
- 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().
- Constant variable are static so we can access constant variable using the class name.
- Best practice for naming the constant variable is to use Pascal casing.
- We can declare a variable as a read-only variable using the readonly keyword in C#.
- 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.
- 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.
- We can use any data type as a read-only variable.
- We can use static keyword with read-only variables.
- 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:
- 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.
- 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.
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.