Does { } act like ( ) when creating a new object in C#?

There are three ways of directly creating a new object in C#:

  • A simple constructor call with an argument list:

    new Foo()       // Empty argument list
    new Foo(10, 20) // Passing arguments
    
  • An object initializer with an argument list

    new Foo() { Name = "x" }       // Empty argument list
    new Foo(10, 20) { Name = "x" } // Two arguments
    
  • An object initializer with no argument list

    new Foo { Name = "x" }
    

The last form is exactly equivalent to specifying an empty argument list. Usually it will call a parameterless constructor, but it could call a constructor where all the parameters have default values.

Now in both the object initializer examples I’ve given, I’ve set a Name property – and you could set other properties/fields, or even set no properties and fields. So all three of these are equivalent, effectively passing no constructor arguments and specifying no properties/fields to set:

new Foo()
new Foo() {}
new Foo {}

Of these, the first is the most conventional.

Leave a Comment