Hi
I was wondering if there is any difference between initializing object like this
MyClass calass = new MyClass()
{
firstProperty = "text",
secondProperty = "text"
}
and initializaing object like this
MyClass calass = new MyClass // no brackets
{
firstProperty = "text",
secondProperty = "text"
}
I was also wondering what is the name of this kind of initialization
Nope, absolutely no difference. In both cases you’re using an object initializer expression. Object initializers were introduced in C# 3.
In both cases, this is exactly equivalent to:
Note how the assignment to
calassonly happens after the properties have been assigned – just as you’d expect from the source code. (In some cases I believe the C# compiler can effectively remove the extra variable and rearrange the assignments, but it has to observably behave like this translation. It can certainly make a difference if you’re reassigning an existing variable.)EDIT: Slight subtle point about omitting constructor arguments. If you do so, it’s always equivalent to including an empty argument list – but that’s not the same as being equivalent to calling the parameterless constructor. For example, there can be optional parameters, or parameter arrays: