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