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.
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.
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With