What is Read-only variable in C#?
In C#, a read-only variable is a variable that can be assigned a value only once, either at the time of declaration or in a constructor, and then cannot be modified again. Once a read-only variable is assigned a value, it remains the same throughout the lifetime of the object that it belongs to.
You can declare a read-only variable using the "readonly" keyword followed by the variable type and name:
class MyClass {
public readonly int myReadOnlyVar; // a read-only variable
public MyClass(int value) {
myReadOnlyVar = value;
}
}
In this example, we declare a read-only variable named "myReadOnlyVar" of type int in the MyClass class. We then assign a value to it in the constructor of the class using the "readonly" keyword. Once the value is assigned, it cannot be changed again.
Read-only variables are useful when you want to ensure that a value is set only once and then cannot be changed. They provide a level of safety and consistency in your code by preventing accidental or intentional modification of a value after it has been set.
No comments:
Post a Comment
If you have any query kindly let me know.