Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why code inside Generic functions ignores overloaded == operator

Tags:

c#

What is the workaround to this problem?

class Program
{
    static void Main(string[] args)
    {
        var a = new Test();
        var b = new Test();
        var eq = Check(a, b);
    }

    private static bool Check<T>(T a, T b) where T : class
    {
        return a == b; //will not call overloaded == 
    }
}
public class Test
{
    public override bool Equals(object obj)
    {
        Test other = obj as Test;
        if (ReferenceEquals(other, null)) return false;
        return true;
    }
    public static bool operator ==(Test left, Test right)
    {
        return Equals(left, right);
    }

    public static bool operator !=(Test left, Test right)
    {
        return !(left == right);
    }
}
like image 257
Alex Burtsev Avatar asked Dec 03 '22 04:12

Alex Burtsev


1 Answers

The == operator is not used because your generic method exists independently of the types you will use for T. It has no way of knowing that all types used as T will overload the == operator... You can use the Equals method instead:

private static bool Check<T>(T a, T b) where T : class
{
    return Equals(a, b);
}
like image 131
Thomas Levesque Avatar answered Dec 05 '22 17:12

Thomas Levesque