Assign to interface array initializator compiles but why?

前端 未结 4 981
星月不相逢
星月不相逢 2020-12-19 02:23

Today I was thinking it would be neat to make anonymous object which is type of some interface, and I have seen on SO that I am not only one.

Before I started checki

4条回答
  •  萌比男神i
    2020-12-19 03:01

    It's worth noting why the compiler lets this behaviour. The reason being someInterface need not be null always. This is what object initializer syntax is translated to:

    Holder temp = new Holder(); //creates temp object calling default constructor
    temp.someInterface = yourValue;
    holder = temp; //finally assigned back to your variable.
    

    In your case someInterface is left uninitialized. But it need not be the case if you have your empty constructor initializing someinterface correctly.

    class Holder
    {
        public Holder()
        {
           someInterface = new Class();
        }
    
        public ISomeInterface someInterface{get; set;}
    }
    

    Now this works:

    Holder holder = new Holder { someInterface = { Property = 1 } };
    

提交回复
热议问题