Monday, February 04, 2008

C# 3.0 Anonymous types - actual type depends on the order of the property assignnments

I learned that the anonymous types in C# 3.0 has got a good feature that, if you have two anonymous declarations with the same signature, then you create only one anonymous type and have two instances of the type.

So, a code fragment like the following is perfectly valid and passes all compiler warnings/errors-

var anon = new { FirstName = "first", Age = 21 };
var anon2 = new { FirstName = "first", Age = 26 };

//this is OK
anon = anon2;

Now, lets take a look into the following code fragment-

var anon = new { FirstName = "first", Age = 21 };
var anon3 = new { Age=16, FirstName = "first2"};

//this doesn't compile
anon = anon3;

So, its evident that the anonymous types are created on the order of the assignments of the properties. However, from my little experience and understanding, I think if this dependency on the exact order wasn't there, then it would make more sense.