Comparison Using Generics

As I was playing with generics, I found something really interesting in terms of comparing two reference types using generic method. For example, when you compare two reference types using == or !=, you are basically comparing the references of those two objects. However when you compare two strings, you are actually comparing two values to see if they are equal instead of comparing references. This is because string class overloads those operators to define a different implementation of == and != operator. When you apply comparisons in generic methods, you would be using the default implementation of == and != that is defined by the object type. This is because the compiler resolves the method using unbound generic type and does not try to accommodate all the possible method calls based on different generic type which may have overloaded the == and != operator. Because of this limitation you may not get the correct comparison achieved in generic method as shown below.

image

 

CWindowssystem32cmd.exe

From the output below, you will notice that first comparison results in the value of true because string overloads the == operator and compares the value instead of reference. However when used in generic, the type is late bound which forces the compiler to use == operator defined by the object type which compares two references and result is false.

No Comments