I have a class ExProperty something like below:
class ExProperty
{
private int m_asimplevar;
private readonly int _s=2;
public ExProperty(int iTemp)
{
m_asimplevar = iTemp;
}
public void Asimplemethod()
{
System.Console.WriteLine(m_asimplevar);
}
public int Property
{
get {return m_asimplevar ;}
//since there is no set, this property is just made readonly.
}
}
class Program
{
static void Main(string[] args)
{
var ap = new ExProperty(2);
Console.WriteLine(ap.Property);
}
}
-
What is the sole purpose of making/using a property readonly or write only? I see, through the following program that
readonlyachieves the same purpose! -
When I make the property read-only, I think it should not be writable. When I use
public void Asimplemethod() { _s=3; //Compiler reports as "Read only field cannot be used as assignment" System.Console.WriteLine(m_asimplevar); }Yes, this is ok.
But, If i use
public ExProperty(int iTemp) { _s = 3 ; //compiler reports no error. May be read-only does not apply to constructors functions ? }Why does the compiler report no error in this case ?
-
Is declaring
_s=3ok? Or should I declare_sand assign its value using a constructor?
Yes, the
readonlykeyword means that the field can be written to only in a field initializer and in constructors.If you want, you can combine
readonlywith the property approach. Theprivatebacking field for the property can be declaredreadonlywhile the property itself has only a getter. Then the backing field can be assigned to only in constructors (and in its possible field initializer).Another thing you could consider is making a
publicreadonlyfield. Since the field itself is read-only, you actually don’t achieve much from the getter if all it does is returning the field value.