Dot Net For All

Deep dive into C# Reference and Value type Equality

In this article I will discuss the two most common ways to compare the value type and reference types in C# in .NET. This can help you to program a bug free solution and not getting any surprises. You can refer here to know about the value types and reference types.

System.Object contains an virtual method known as Equals. It also contains the operator overloading for the equality operator “==”.

Equality For Reference Type

Equality Using System.Object Equals() Method

Equality using “==” operator

Equality For Value Types

How the Equality Comparer(“==”) compares the Values

Please check the below code.

            int i = 1;
            int i1 = 2;
            i.Equals(i1);
            if(i == i1)
            {

            }

The IL code generated for the above two equality comparisons is as shown in the below figure.

Equality for Value Types

As seen in the above code the Equals method calls the Eqauls method of the integer. While the “==” operator calls the ceq instruction.

This instruction compares the values directly from hardware using CPU’s register. It checks the values in both the registers are different in our case.

If we repeat the above process for the reference type i.e comparing two reference variables using Object.Equals() and “==”. For both the cases the result will be false as we know that both of these comparisons use reference equality.

But if we check the ildasm code for both the comparison we will see that “==” operator emits code to check the equality using ceq as in the previous case. But since the operands are  the reference type the registers will contain the address location in the memory which is different for two different references.

Conclusion:

I hope I have covered enough for the equality for the value types and reference types in this article. This is the simple topic but can create some undesired results in the C# application if we are not aware about the internals of equality.

Reference

PluralSight : C# Equality and Comparison

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview