This question already has an answer here:
This error pops up when I'm trying to retrieve a value from a class object. It is after implementing the readonly keyword in a get-only property, does it show. What I understand so far is that implementing "readonly" only limits the class property to a get method. I'm not too sure about how to implement the keyword, some help please?
Here's the current code.
class Counter
{
private int _count;
private string _name;
public Counter(string name)
{
_name = name;
_count = 0;
}
public void Increment()
{
_count++;
}
public void Reset()
{
_count = 0;
}
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public readonly int Value
{
get
{
return _count;
}
}
}
For a property to be read only, the following is sufficient:
public int Value { get { return _count; }}
The readonly
keyword, is to make read only fields, which can only be set in the constructor.
class Age
{
readonly int year;
Age(int year)
{
this.year = year;
}
void ChangeYear()
{
//year = 1967; // Compile error if uncommented.
}
}
Btw, as a short-cut you can write:
public int Value { get; private set;}
You now have a property with a public getter, and a private setter, therefor it can only be set within an instance of this class (and through evil reflection).
readonly
-field. - HimBromBeere
readonly
is neither necessary nor allowed here. The fact that you've only supplied a getter is enough to indicate the property is read-only. - Jeroen Mostertreadonly
modifier only applies to fields. - CodeCaster