Is there a way to make readonly (not just private) automatic properties?

前端 未结 6 552
日久生厌
日久生厌 2020-12-31 13:02

Automatic properties let me replace this code:

private MyType myProperty;
public MyType MyProperty
{
    get { return myPropertyField; }
}

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-31 13:40

    No, unfortunately not. I would very much like the feature, which could look like this:

    public readonly string Name { get; }
    

    or (slightly oddly)

    public readonly string Name { get; readonly set; }
    

    This would be converted into something like:

    private readonly string <>_Name;
    
    public string Name { get { return <>_Name; } }
    

    The twist is that setter calls would be allowed - but only within the constructor. Such calls would be converted directly into assignments to the backing field.

    I would dearly, dearly love such a feature. Maybe for C# 5...

提交回复
热议问题