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?
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?
Nothing. The ()
is redundant. The only thing required is that the object has a default constructor.
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.
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
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"
}
There is no difference. You can omit the empty braces in this case. For the compiler, those two are 100% equivalent.