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
An object initializer is an expression that describes the initialization of an Object . Objects consist of properties, which are used to describe an object. The values of object properties can either contain primitive data types or other objects.
Java offers two types of initializers, static and instance initializers.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With