Wednesday, April 27, 2011

Comparing Anonymous Types

If you have multiple anonymous types that have the same Properties, with the same type and in the same order then the compiler treats them as the same type.

For example, if I have two anonymous types declared as follows

var a = new { Name = "Peter" };
var b = new { Name = "Peter" };

The compiler sees these as the same type (the Properties are both called Name, they are both of type string and all the Properties are in the same order). Because Anonymous Types inherit from System.Object you can check if these two instances are equal using Equals(). Anonymous Type instances will be equal if their properties are equal. So the following outputs "True" because the Name properties are equal (strings that match exactly).

Console.WriteLine(a.Equals(b));

However, if I changed the case of one the Names to "peter", this would result in "False" because the two properties are no longer equal - String overrides Equals and ignores case in the checking for equality. It is also worth noting that using operators when checking for equality will not give you the result you might be expecting. You cannot have any members in an Anonymous Type other than Read-Only Properties meaning you cannot override a method from System.Object including operators. So the following code results in "False".

var a = new { IsAnon = true };
var b = new { IsAnon = true };
Console.WriteLine(a == b);

No comments:

Post a Comment