Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't readonly be used with properties [duplicate]

Tags:

c#

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; }
}
like image 476
Stralos Avatar asked Dec 10 '15 07:12

Stralos


2 Answers

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; }}
like image 141
quadroid Avatar answered Sep 19 '22 12:09

quadroid


If you want to keep properties read only, you may just define their getter like this:

public MyProperty { get; }
like image 34
Ovais Khatri Avatar answered Sep 18 '22 12:09

Ovais Khatri