4

What is the resulting difference between these two class initializers? Both seem to be syntactically correct in C#. Is the second one a shortcut for the first?

Class1 class1 = new Class1()
{
    Boolean1 = true,
    Class2Instance = new Class2
    {
        Boolean2 = true,
    },
};

and

Class1 class1 = new Class1()
{
    Boolean1 = true,
    Class2Instance =
    {
        Boolean2 = true,
    },
};

I ask because obviously it is not valid to do this:

Class1 class1 =
{
    Boolean1 = true,
    Class2Instance = new Class2()
    {
        Boolean2 = true,
    },
};
Itzalive
  • 370
  • 4
  • 14

1 Answers1

1

The two examples you gave are not exactly the same. Using a tool like ILSpy you can check what the complier creates for the two statements.

The first one compiles to something like the following (decompiled using ILSpy):

Class1 expr_06 = new Class1();
expr_06.Boolean1 = true;
expr_06.Class2Instance = new Class2
{
    Boolean2 = true
};

Whereas the second example compiles to the following (decompiled using ILSpy):

Class1 expr_06 = new Class1();
expr_06.Boolean1 = true;
expr_06.Class2Instance.Boolean2 = true;

As you can see, in the second example the creation of the Class2Instance with the new-keyword is missing and you'll get a NullReferenceException when running this code.

However, you can prevent getting a NullReferenceException in the second example when you create a new Class2Instance within the constructor of your Class1:

class Class1
{
  public Class1()
  {
    Class2Instance = new Class2();
  }
}
M.E.
  • 2,759
  • 3
  • 24
  • 33