7

Possible Duplicate:
Why are C# 3.0 object initializer constructor parentheses optional?

What is the difference between instatiating an object by using

classInstance = new Class() { prop1 = "", prop2 = "" };

and

classInstance = new Class { prop1 = "", prop2 = "" };

Community
  • 1
  • 1
kavun
  • 3,358
  • 3
  • 25
  • 45

3 Answers3

6

Short answer: Nothing. The () can be used if you want to pass in some constructor args but in your case since you don't have any, you can skip ().

For eg. () is useful here.

  Foo foo = new Foo(someBar){Prop1 = "value1", Prop2 = value2};

but if you are trying to call the parameter-less constructor, it's optional

  Foo foo = new Foo {Prop1 = "value1", Prop2 = value2};
Bala R
  • 107,317
  • 23
  • 199
  • 210
4

Nothing. The second is just a short-cut for the first. The first allows you to include arguments to a constructor. So, you can't use the short-cut if the class doesn't have an empty constructor.

You may have an interest in this question:

Why are C# 3.0 object initializer constructor parentheses optional?

And Eric Lippert´s great blog post:

Ambiguous Optional Parentheses, Part One

Community
  • 1
  • 1
Lasse Espeholt
  • 17,622
  • 5
  • 63
  • 99
3

There is no difference other than syntax, you are still calling the parameter-less constructor either way.

Jon Erickson
  • 112,242
  • 44
  • 136
  • 174