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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…