4

I define objects from class in C# this way

var something = new SomeThing()
{
    Property = "SomeProperty"
}

and this way

var something = new SomeThing
{
    Property = "SomeProperty"
}

what is the difference between these definitions?

aikutto
  • 582
  • 2
  • 8
  • 22

5 Answers5

6

Nothing. The () is redundant. The only thing required is that the object has a default constructor.

DaveDev
  • 39,517
  • 70
  • 210
  • 376
3

There's no difference as such. Parentheses are optional when using a function as a constructor (with the new operator and no parameters). Parentheses are always required when calling a function when you do not use the new operator.

MusicLovingIndianGirl
  • 5,817
  • 8
  • 33
  • 65
3

You can omit the parentheses, the default constructor will be used (assuming one is available).

When using object initializers, you only need to use parentheses if you want to specify a different constructor.

Eric Lippert's take on why the parentheses were made optional: https://stackoverflow.com/a/3661197

Community
  • 1
  • 1
dcastro
  • 63,281
  • 21
  • 137
  • 151
3

Nothing, when the parentheses are empty.

They only make sense when you provide a parameter; you can do that at the same time:

var something = new SomeThing("some other value")
{
    Property = "SomeProperty"
}
Kjartan
  • 17,961
  • 15
  • 70
  • 90
2

There is no difference. You can omit the empty braces in this case. For the compiler, those two are 100% equivalent.

nvoigt
  • 68,786
  • 25
  • 88
  • 134