Comparing Anonymous Types
C# 3.0 allows you to create anonymous types which is basically a handy way to use a class without defining a class. It is really a nice feature when you are building linq queries which does not return fixed number of columns depending on the query you write. When you write an anonymous class, compiler in the background creates a auto generated class with those properties. If you define two anonymous types with the same property name and data type and in the same order, compiler will only create 1 anonymous type in the background and it will reuse that auto generated class in both those anonymous declarations.However if the definition of the anonymous type changes compiler will generate a new class. Because of the reuse of class, you have the ability to compare to generic classes having the same structure. Not only can you compare two anonymous classes but can also do assignment when two anonymous classes have the same structure. Let's have a look at an example that illustrates this behavior.
In the above example, I start with two anonymous classes with same property names and types and declared in the same order. The next anonymous type is slight different where I change the order of properties declared. This results in compiler generating a new anonymous type in the background. Since sametype1 and sametype2 are same anonymous types, I can compare those two types without compilation error. The reference type compare results in a value of False being outputted to the screen since those types do not have the same reference. However when I try to compare sametype1 and notsame variable, it results in a compilation error since those types are structurally different. In the next portion, you will notice that I was able to assign sametype1 to sametype2 because they were defined as same anonymous types, however when I try to assign sametype1 to notsame, compilation error occurs.