While reading Jon Skeets book C# in Depth I noticed he mentioned that when using anonymous types it's important that the name and type are the same for the properties. As well as the order. Since the underlying type is using generics it will generate two types when the order of the properties are reversed.
For example, take a look at the following C# code:
var idName = new { Name = "Volvo", Id = 28 };
var idName2 = new { Name = "SAAB", Id = 29 };
What's actually generated under the hood by the compiler looks like this in IL code:
1: L_0001: ldstr "Volvo"
2: L_0006: ldc.i4.s 0x1c
3: L_0008: newobj instance void <>f__AnonymousType4`2<string, int32>::.ctor(!0, !1)
4: L_000d: stloc.0
5: L_000e: ldstr "SAAB"
6: L_0013: ldc.i4.s 0x1d
7: L_0015: newobj instance void <>f__AnonymousType4`2<string, int32>::.ctor(!0, !1)
8: L_001a: stloc.1
As you can see the type is constructed with the use of generics, where the order of the properties are used. In this example the type will be created with <string, int32>, and both of the objects will be of the same type.
However, if the properties are reversed:
var idName = new { Name = "Volvo", Id = 28 };
var nameId = new { Id = 29, Name = "SAAB" };
The IL code generated is changed:
1: L_0001: ldstr "Volvo"
2: L_0006: ldc.i4.s 0x1c
3: L_0008: newobj instance void <>f__AnonymousType4`2<string, int32>::.ctor(!0, !1)
4: L_000d: stloc.0
5: L_000e: ldc.i4.s 0x1c
6: L_0010: ldstr "SAAB"
7: L_0015: newobj instance void <>f__AnonymousType5`2<int32, string>::.ctor(!0, !1)
8: L_001a: stloc.1
This time, a new type is generated for the second object where generic initialization is reversed to <int32, string>.
Types are re-used by the compiler within one assembly, but within one assembly it's wise to make sure that the properties are in the same order. Thanks to Resharper life's much easier with their detection of this kind of problems. If you're trying to initialize an anonymous type with the properties reveresed Resharper (I'm using v4.1) pops up and says: "Similar anonymous type detected nearby. Are they the same?"

Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5