-2

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! :) )

Ðаn
  • 10,400
  • 11
  • 57
  • 90
RedPelle
  • 205
  • 3
  • 16

1 Answers1

3

That is because you don't create a new Prop2. Instead you are assigning a new value to Prop2.Prop, which fails since Prop2 is null.

Prop2 = { Prop = "TEST2" }

Is similar to:

testObj.Prop2.Prop = "TEST2";

Which fails for aforementioned reason.

The new ... variant is actually:

Type1 testObj = new Type1();
testObj.Prop1 = "TEST",
var x = new Type2();
x.Prop = "TEST2";
testObj.Prop2 = x;
Patrick Hofman
  • 143,714
  • 19
  • 222
  • 294