Sitecore Swamp

Dive in the Sitecore Swamp

NAVIGATION - SEARCH

The Order of Properties in Object Initializer (C#)

For sake of simple programming, I use object initialier quite often. But I never payed attention to the order of the perproties until comes to this one:

var index = 0;
var obj = new 
{
    property1 = fields[index++], 
    property2 = fields[index++], 
    ..., 
    propertyn = fields[index++]
};

The reason doing this is assign each element in the fields to the according property in the obj. So if the property setter is called in the different order from the object initializer, I will be in trouble. The benefit of it is that I can adjust the order of property to accommodate the fields order.



Let's think a different way of object initializer, the curly bracket { } means a sequence in c# in my understanding, like code block and list. As stated in the C# Specification (5.0): 


An instance of Point can be created and initialized as follows:

Point a = new Point { X = 0, Y = 1 };

which has the same effect as

Point __a = new Point();
__a.X = 0;
__a.Y = 1;
Point a = __a;

So it looks the order property setter can be guaranteed to be the same order of in the initializer.





New language features in C# 6

Before looking into the new in C# 6, let look back the history of the C# language:

json2csharp

http://json2csharp.com/

[

   {
      "firstname":"Jeff",
      "lastname":"Wang",
      "boys":[
         {
            "firstname":"Daniel",
            "lastname":"Wang"
         },
         {
            "firstname":"Brandon",
            "lastname":"Wang"
         }
      ],
   }
]

=> 

public class Boy
{
    public string firstname { get; set; }
    public string lastname { get; set; }
}

public class RootObject
{
    public string firstname { get; set; }
    public string lastname { get; set; }
    public List<Boy> boys { get; set; }
}