Why properties in C# cannot be readonly ?
When I try to have a property readonly it states that:
a modifier 'readonly' is not valid for this item
Simmilar question was asked here: Why can't properties be readonly? But the question was asked 5 years ago, and the answer provided then was: Because they didn't think it thru. Is this still the case after 5 years?
edit: Code example:
public class GreetingClass
{
public readonly string HelloText { get; set; }
}
Properties can be readonly in C#, the implementation is just not using the readonly keyword:
If you use C#6 (VS 2015) you can use the following line, which allows assigning the property in either the constructor or in the member definition.
public int Property { get; }
If you use an older C# / Visual Studio Version you can write something like this, and assign the field in the constructor or the field definition:
private readonly int property;
public int Property { get { return this.property; }}
If you want to keep properties read only, you may just define their getter like this:
public MyProperty { get; }
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