Assignment to readonly property in initializer list

前端 未结 3 1187
生来不讨喜
生来不讨喜 2020-12-21 10:01

Can one tell me, why the heck does it compile?

namespace ManagedConsoleSketchbook
{
    public interface IMyInterface
    {
        int IntfProp
        {
           


        
相关标签:
3条回答
  • 2020-12-21 10:35

    This is a nested object initializer. It's described in the C# 4 spec like this:

    A member initializer that specifies an object initializer after the equals sign is a nested object initializer - that is, an initialization of an embedded object. Instead of assigning a new value to the field or property, the assignments in the nested object initializer are treated as assignments to members of the field or property. Nested object initializers cannot be applied to properties with a value type, or to read-only fields with a value type.

    So this code:

    MyClass foo = new MyClass { Property = { IntfProp = 5 }};
    

    would be equivalent to:

    MyClass tmp = new MyClass();
    
    // Call the *getter* of Property, but the *setter* of IntfProp
    tmp.Property.IntfProp = 5;
    
    MyClass foo = tmp;
    
    0 讨论(0)
  • 2020-12-21 10:35

    Because you are using the initializer which uses the setter of ItfProp, not the setter of Property.

    So it will throw a NullReferenceException at runtime, since Property will still be null.

    0 讨论(0)
  • 2020-12-21 10:35

    Because

    int IntfProp {
        get;
        set;
    }
    

    is not readonly.

    You did not invoke setter of MyClass.Property, just getter.

    0 讨论(0)
提交回复
热议问题