Different kinds of object initialization
Hi I was wondering if there is any differe开发者_开发问答nce 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:
// tmp is a hidden variable, effectively. You don't get to see it.
MyClass tmp = new MyClass();
tmp.firstProperty = "text";
tmp.secondProperty = "text";
// This is your "real" variable
MyClass calass = tmp;
Note how the assignment to calass
only 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:
using System;
class Test
{
int y;
Test(int x = 0)
{
Console.WriteLine(x);
}
static void Main()
{
// This is still okay, even though there's no geniune parameterless
// constructor
Test t = new Test
{
y = 10
};
}
}
Nope. In fact, ReSharper would complain that the brackets of a parameterless constructor with initializer are redundant. You would (obviously) still need them if you were using a constructor with one or more parameters, but since this isn't the case just remove them.
精彩评论