Initializing various types of objects

Hi I was wondering if there is a difference between initializing an object like this.

MyClass calass = new MyClass() { firstProperty = "text", secondProperty = "text" } 

and an initializing object like this

 MyClass calass = new MyClass // no brackets { firstProperty = "text", secondProperty = "text" } 

I was also interested in what is the initialization name of this type

+4
source share
2 answers

No, absolutely no difference. In both cases, you use an object initializer expression. Object initializers were introduced in C # 3.

In both cases, this is exactly equivalent:

 // 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; 

Notice how the calass happens only after the properties have been assigned - as you would expect from the source code. (In some cases, I believe that the C # compiler can effectively remove an additional variable and change the order of assignments, but it should behave like this translation. Of course, this can make a difference if you reassign an existing variable.)

EDIT: Minor thin point about skipping constructor arguments. If you do this, it is always equivalent to including an empty argument list, but it is not the same as calling the constructor without parameters. For example, there may 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 no geniune parameterless // constructor Test t = new Test { y = 10 }; } } 
+8
source

Nope. In fact, ReSharper complains that the brackets of a parallel constructor with an initializer are superfluous. If you were to use a constructor with one or more parameters, you would (obviously) still need them, but since this is not the case, just delete them.

+2
source

Source: https://habr.com/ru/post/1341901/


All Articles