I noticed a strange behaviour from C# compiler that I can't explain.
Suppose you want to initialize a new object in this way:
Type1 testObj = new Type1 {
Prop1 = "TEST",
Prop2 = new Type2 { Prop = "TEST2" }
};
Everything goes fine. Compiler won't complain and no runtime exception will be thrown.
I tried to inizialize in a similar way, by removing the explicit new Type2
from the code, like this:
Type1 testObj = new Type1 {
Prop1 = "TEST",
Prop2 = { Prop = "TEST2" }
};
Compiler will not complain, but in runtime an error will be thrown:
System.NullReferenceException: Object reference not set to an instance of an object.
I noticed that I can't remove new Type1
because in this case compiler will complain. Compilation succeeds just when I remove the "new" keyword in a property initialization, not in the main object.
Visual Studio does not show me any typing error and suggests me the object properties correctly (.NET Fiddle as well) because types seems to be inferred (and tooltips give the right informations about this).
Here is a working demo: https://dotnetfiddle.net/vnlI20
Here is a not working demo: https://dotnetfiddle.net/0CraIU
Can someone explain this behaviour? Are there any cases in which you can avoid the new keyword, without any compiler or runtime error? (It would be cool! :) )