Read Only
Read Only Fields
When the value of a field is only visible outside the class it is called a read only property.
The value of the field can only be changed inside the class.
public class Animal
{
private readonly int _Age;
}
The readonly keyword is used to declare a constant that can be defined in its declaration or at run-time in the constructor.
This value cannot be changed after the class has been created.
The const keyword is used to declare a constant that must be defined in its declaration.
A read-only field is similar to a const and can also represent values that do not change
A read-only field can either be initialized at the declaration or in a constructor.
A read-only field can be complex types.
A read only field that contains an object can have its properties modified at run-time
A private set property can be called after the class has been created.
Read Only Properties
To create a read-only property you can exclude the set altogether.
public class Animal
{
private int _Age;
public int Age
{
get { return this._Age; }
}
}
Alternatively if you still needed to set the value inside the class then you can change it to private.
public class Animal
{
private int _Age;
public int Age
{
get { return this._Age; }
private set { this._Age = value; }
}
}
© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext