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
  • 592
  • 2
  • 8
  • 22

5 Answers5

6

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

DaveDev
  • 41,155
  • 72
  • 223
  • 385
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,909
  • 9
  • 34
  • 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
  • 66,540
  • 21
  • 145
  • 155
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
  • 18,591
  • 15
  • 71
  • 96
2

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

nvoigt
  • 75,013
  • 26
  • 93
  • 142