Comparing two generic type variables with each other

  1. What is happening when we trying to compare two generic type variables?
  2. How to make possible comparing reference types?
  3. Why we can’t compare two value type variables?

We can’t compare two generics type variables because the C# compiler knows nothing about specified types. We can make possible comparing reference types using the class constrain. However we can’t compare two value types because the C# compiler knows nothing about comparing value types. The C# compiler can emit code which compares primitive types but we can constrain generics method only with interfaces, non-sealed classes and other type parameters.

 

Example 1:

        //Operator ‘==’ cannot be applied to operands of type ‘T’ and ‘T’     

private static void ComparingTwoGenericStructTypeVariables<T>(T o1, T o2) where T : struct

{

if (o1 == o2) { } // Error

}

 

Example 2:

        //’int’ is not a valid constraint. A type used as a constraint must be an interface,

        //a non-sealed class or a type parameter.

private static void ComparingTwoGenericTypeVariables<T>(T o1, T o2) where T : int

{

if (o1 == o2) { } // Error

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s