2013-01-25

C# Blooper №12: 'Where' constraints not included in method signatures


Before reading any further, please read the disclaimer.

When writing generic methods in C#, it is possible to use the 'where' keyword to specify constraints to the types that the generic parameters can take. Unfortunately, these constraints cannot be used for resolving overloaded methods. Case in point:

namespace Test12
{
    class Test
    {
        public static bool Equals<T>( T a, T b ) where T: class
        {
            return object.Equals( a, b );
        }

        public static bool Equals<T>( T a, T b ) where T: struct //error CS0111: Type 'Test' already defines a member called 'Equals' with the same parameter types
        {
            return a.Equals( b );
        }
    }
}

-

No comments:

Post a Comment