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.
new(to make an anonymous type) or anew()(implicit type for constructor, with an initializer). If you omit the type (someObject = { Prop1 = ... }) it is legal as initialization syntax for a property or field, but only in the context of creating another object (i.e.new ContainingObject { someObject = ... }). Do you have the context in which this line occurred, or possibly a correction of what the exact line was? C# by now has acquired many such "initialization shorthands".var parentObjecct = new ParentObject(){ SomeObject = { Prop1="1", Prop2="2", Prop3="3"}};But still, SomeObject is an object, how can we initialize it with list notation?Addcalls), that's a nested object initializer. It has been legal since C# 3 (so quite a while now). It's simply shorthand forvar o = new ParentObject(); o.SomeObject.Prop1 = "1"; o.SomeObject.Prop2 = "2"...Note that this requires thatParentObjectinitializeSomeObjectto an instance, otherwise it'll fail -- the sytax merely assigns, it doesn't create (in this it resembles collection initializers, which merely call.Addwithout creating).