I was working on one of our new applications when I made a stupid mistake… I forgot to write: ”new ClassName” inside an object initializer. Strangely VS just compiled the code… without any error or warning. (I’ve used VS 2015, .Net 4.5.2)
My Code:
var target = new MyClass
{
MyValues = new List<MyOtherClass>
{
new MyOtherClass
{
Start = new DateTimeValue
{
DateTime = new DateTime(2015, 08, 23)
},
End = {
DateTime = new DateTime(2015, 08, 23)
}
}
}
};
(Start and End are both of type DateTimeValue)
When I start the application, this code has thrown a NullReferenceException. (Adding “new DateTimeValue” fixed the problem). Why was there no error from the compiler?
There's nothing wrong there at all. It's using an object initializer for
End
which sets properties using the existing value instead of assigning a new value toEnd
. Your code is equivalent to:From the C# 5 specification, section 7.6.10.2:
That's exactly what you're doing here - the
{ DateTime = ... }
part is an object initializer.