Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

c# - Assign to interface array initializator compiles but why?

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 checking out what happens I wrote some code like the one below. To my amusement it compiled, I am using .net framework 4 and I know there is no way to do anonymous objects implement interface, but I have not seen complaint from VS about this code.

Even better when I put braces intelisense is finding "Property" of my interface, just like it would be valid code.

Why is this piece compiling and when ran it is giving null reference exception?

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            Holder holder = new Holder { someInterface = { Property = 1 } };
            Console.WriteLine(holder.someInterface.Property);
        }
    }

    class Holder
    {
        public ISomeInterface someInterface{get; set;}
    }

    interface ISomeInterface
    {
        int Property { get; set; }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Holder holder = new Holder { someInterface = { Property = 1 } };//<--Note you missed new keyword

Above line is equal to

Holder temp = new Holder();
temp.someInterface.Property = 1;
Holder holder = temp;// <--Here someInterface is null so you get null reference exception. 

This should be something like

Holder holder = new Holder { someInterface = new SomeClass(){ Property = 1 } };//<--Note the new keyword here

Note: Your code never introduced "Anonymous Type" It is an "Object Initializer".

When you use ObjectInitializer syntax with new keyword it means you're setting something, when you use ObjectInitializer syntax without new keyword it means you're reading something.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...