Anonymous Type and Equality Check in C#

Anonymous type is a feature in C# that was introduced with C# 3.0 which provides the developers the option to encapsulate the read only properties in to a object without explicitly defining the type. When using anonymous type in C# , there are times when you want to perform the equality check on the same. How is the equality check made on them ?

Anonymous Type and Equality Check in C#

If the anonymous types that are compared have the same number of members , same order and the same types , the equality operator returns true. When the anonymous type that have any one of the above (order , number of members and type) being different , the equality operator would produce a different hash value and would return false.

Below is a sample code snippet demonstrating the equality check of the anonymous type in C#.

using System;

namespace DeveloperPublishApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            var Employee1 = new
            {
                Name ="Senthil Kumar",
                CompanyName = "Trivium eSolutions"
            };
            var Employee2 = new
            {
                Name = "Senthil Kumar",
                CompanyName = "Trivium eSolutions"
            };
            var Employee3 = new
            {                
                CompanyName = "Trivium eSolutions",
                Name = "Senthil Kumar"
            };
            var Employee4 = new
            {
                Name = "Norton Stanley",
                CompanyName = "Trivium eSolutions",                
            };
            Console.WriteLine(Employee1.Equals(Employee2)); // True - because everything is same
            Console.WriteLine(Employee1.Equals(Employee3)); // False - because the order of member is different
            Console.WriteLine(Employee1.Equals(Employee4)); // False - values are different
            Console.ReadLine();
        }
     
    }
}


image

2 thoughts on “Anonymous Type and Equality Check in C#

  1. “var” has **nothing** to do with anonymous types. Use var to infer the type based on the declaration. Inference applies whether it is anonymous, static, or dynamic (read: anything!).

    You have correctly identified the equality comparisons for anonymous types, so maybe your article should stick to that?

    • Hi Tommy ,

      Thanks for the comment . Appreciate it 🙂

      Yes , I agree with you . The confusion was caused because I had put the var keyword in the bracket next to the anonymous type . Now , it is updated . Thank you .

      Regards,
      Senthil

Leave a Reply

Your email address will not be published. Required fields are marked *