In a .NET application when should I use “ReadOnly” properties and when should I use just “Get”. What is the difference between these two.
private readonly double Fuel= 0;
public double FuelConsumption
{
get
{
return Fuel;
}
}
or
private double Fuel= 0;
public double FuelConsumption
{
get
{
return Fuel;
}
}
Creating a property with only a getter makes your property read-only for any code that is outside the class.
You can however change the value using methods provided by your class :
Setting the private field of your class as
readonlyallows you to set the field value only in the constructor of the class (using an inline assignment or a defined constructor method).You will not be able to change it later.
readonlyclass fields are often used for variables that are initialized during class construction, and will never be changed later on.In short, if you need to ensure your property value will never be changed from the outside, but you need to be able to change it from inside your class code, use a "Get-only" property.
If you need to store a value which will never change once its initial value has been set, use a
readonlyfield.