This question came up in the comments of this answer. The inability to have readonly properties was proposed as a potential reason to use fields instead of properties.
For example:
class Rectangle
{
private readonly int _width;
private readonly int _height;
public Rectangle(int width, int height)
{
_width = width;
_height = height;
}
public int Width { get { return _width; } }
public int Height { get { return _height; } }
}
But why can't you just do this?
public int Width { get; readonly set; }
Edit (clarification): You can achieve this functionality in the first example. But why can't you use the auto-implemented property shorthand to do the same thing? It would also be less messy, since you wouldn't have to directly access the fields in your constructor; all access would be through the property.
Edit (update): As of C# 6.0, readonly properties are supported! object MyProp { get; }
This property can be set inline (object MyProp { get; } = ...
) or in the constructor, but nowhere else (just like readonly
fields).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…