C # Initializer Syntax

For this class setting.

public class X { public Y YInstance; public X() { YInstance = new Y(); } } public class Y { public long Z; } 

I had this code.

 var x = new X(); x.YInstance.Z = 1; 

Resharper had a hint of using an object initializer that converted my code to this.

 var x = new X { YInstance = { Z = 1 } }; 

I am familiar with the usual initialization of objects using parentheses to populate properties, but I'm not sure what this does. Looking at IL, it doesn't seem to set YInstance with a new anonymous class, which was my first guess. It will also not be the same functionality as before, which would be strange for Resharper.

I'm just looking for a keyword for a search keyword or a simple explanation.

+5
source share
1 answer

The syntax is arbitrary, strictly speaking, but, in my opinion, a way to think that YInstance = { Z = 1 } does not have the new keyword, so it does not call any constructors. However, there is a part of the syntax initializer, so it simply applies the initializer to the properties of the existing one! YInstance YInstance exists in your case because you created it in your X constructor. Here's what happens if you havenโ€™t .

Instead of "Set YInstance for this thing," "Set YInstance properties for these things."

= { ... } in this case means applying this initializer to an existing property value.

The indication that c = between the name of the property and the initializer bindings may at first seem uninteresting, but that it is and like any syntax, you will learn to recognize it quickly enough. You can do the same to initialize the elements of already created collections:

 public class C { public List<int> Items { get; } = new List<int>(); } 

...

 // This can't be assigning to Items, because it read-only var c = new C { Items = { 0, 1, 2 } }; 

One of the C # team members (if you specify his name, he will appear) after he kindly took the time to comment on the answer to the question about the syntax of the list initializer . They kicked him a lot, but that was the best option they encountered. There are many considerations when it comes to adding syntax for a mature language. They lose a lot of sleep in order to make it clear to the programmer, but at the same time it must be unambiguous for the compiler, it cannot break the existing code, etc. "Syntax is arbitrary" does not mean that the C # team makes arbitrary decisions.

I canโ€™t say why Resharper would mind you taking a weapon against a sea of โ€‹โ€‹braces. I like your original version.

+8
source

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


All Articles