1

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;
        }
    }
}


  • 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 Mostert
  • A property with only a getter is already readonly. The readonly modifier only applies to fields. - CodeCaster

1 답변


5

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.

Example:

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).


  • "through evil reflection" which would also appy to a readonly-field. - HimBromBeere
  • @HimBromBeere: good point. These access modifiers are only to guide developers while building their applications. It does not offer any security or protection in any way. - Stefan

Linked


Related

Latest