'strange C# object initialization notation
Whilst working in a codebase I found a line of code that seemed to initialize an CustomObject (ObservableObject to be precise) as follows:
CustomObject someObject = {Prop1="1", Prop2="2", Prop3="3"}
where CustomObject has three string properties Prop1, Prop2, Propr3. The problem is that I have not been able to reproduce such an initialization in a sample project of my own. What is this notation called? To me it seems as though list notation is used to initialize a custom object...how is this possible? It's certainly not an anonymous type that is being created.
Solution 1:[1]
What you are seeing is a default property settings construction of the class.
By default, you may see
var SomeObject = new SomeObjectClass();
SomeObject.Prop1 = "1";
SomeObject.Prop2 = "2";
SomeObject.Prop3 = "3";
By using the curly brackets does the implied same result. You are just stating... give me an instance of a given object, and by the way, please set the following properties to these default values I'm providing via...
var SomeObject = new SomeObjectClass{
SomeObject.Prop1 = "1",
SomeObject.Prop2 = "2",
SomeObject.Prop3 = "3" };
Now, in the sample context you have provided there is no "new" of a given class trying to be created.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DRapp |
