Using object initializer and parenthesis

  • Thread starter Thread starter K Viltersten
  • Start date Start date
K

K Viltersten

When i initialize an object, the syntax goes
as follows (note the lack of parentheses).

var name = MyClass { Property = 5; }

My collegaues argued yesterday that the
correct (or at least more intuitive) approach
would be to add "()" as follows.

var name = MyClass() { Property = 5; }

While both sytaxes are correct, i wonder if
there's a guideline or a general concensus
regarding this difference. Perhaps just a
matter of taste?
 
K Viltersten said:
When i initialize an object, the syntax goes
as follows (note the lack of parentheses).

var name = MyClass { Property = 5; }

My collegaues argued yesterday that the correct (or at least more
intuitive) approach
would be to add "()" as follows.

var name = MyClass() { Property = 5; }

While both sytaxes are correct, i wonder if
there's a guideline or a general concensus regarding this difference.
Perhaps just a matter of taste?

In this particular case it is a matter of taste. The reason for
including the parenthesis is that you may call a non-default constructor and
provide the arguments for the constructor in between the parenthesis, and
then provide values for various properties in between the braces.

If you are not going to provide any paremeters for the constructor, then
both constructs are equivalent. I find myself that I tend to use the second
one (with parenthesis) most of the time, but I don't have any specific
reason for doing so. I have tried compilig both calls, and then looking at
the resulting code using ILDASM, and both happen to produce exactly the same
IL:

IL_0000: nop
IL_0001: newobj instance void Test1.MyClass::.ctor()
IL_0006: stloc.2
IL_0007: ldloc.2
IL_0008: ldc.i4.1
IL_0009: callvirt instance void Test1.MyClass::set_Something(int32)
IL_000e: nop
IL_000f: ldloc.2
IL_0010: stloc.0
 
Back
Top