Can one tell me, why the heck does it compile?
namespace ManagedConsoleSketchbook
{
public interface IMyInterface
{
int IntfProp
{
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;
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
.
Because
int IntfProp {
get;
set;
}
is not readonly.
You did not invoke setter of MyClass.Property
, just getter.