Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CS0106 compile error: readonly property and getter

It might look foolish but I wonder why the following code produces me CS0106 compile-time error:

error CS0106: The modifier 'readonly' is not valid for this item

The code:

class MyClass
{
private readonly int _value
{
  get
  {
    if (_value < 0)
      return -1 * _value;
    return _value;
  }
}

In my understanding I do nothing wrong inside get as I just read the value. I agree that calculations for readonly's property getter look awkward from the logical point of view.

P.S. Code inside get has no practical sense - it is just a "something that reads the _value"

UPDATE

In short initially I thought that it would be quite logic to make a readonly property by using readonly keyword. I missed the main thing about readonly property that is available from Microsoft documentation:

The readonly keyword is a modifier that you can use on fields.

like image 228
nickolay Avatar asked Apr 07 '16 20:04

nickolay


2 Answers

No sarcasm... You get a compile error because it's not part of the grammar for the language.

First, By nature of having only a get, then you're already making the property "readonly".

Second, you need to think of the property as syntactic sugar around two methods int getValue() and void setValue (int). Would it make sense to set the methods as "readonly"?

Third, setting the property as readonly wouldn't make sense since the property as a construct is not mapped to anything in memory. See the previous point about how it's basically a nice way of writing (up to) two methods.

like image 160
Babak Naffas Avatar answered Sep 30 '22 11:09

Babak Naffas


Implementing only Get for a property is like already readonly. so if you want to achieve implementing the similar behavior, below will be the working code.

class MyClass
{
    private readonly int _value = -5; // < some value> or<set it in the constructor>;
    private int ReadableValue
    {
        get
        {
            return Math.Abs(_value); 
        }
    }
}
like image 24
Abhilash R Vankayala Avatar answered Sep 30 '22 11:09

Abhilash R Vankayala