0

I am trying to write a generic equality comparer. I've written the following code.

public static bool Equals<T>(T t1, T t2)
{
    bool result;
    if (typeof(T).IsPrimitive)
    {
        result = t1 == t2;
    }
    else
    {
        if (t1 == null)
        {
            result = t2 == null;
        }
        else
        {
            result = t1.Equals(t2);
        }
    }
    return result;
}

However due to the compile error Operator '==' cannot be applied to operands of type 'T' and 'T' for the line result = t1 == t2;, I cannot use this code. Is there any other way to achieve this? I want to be able to use this method on any T (class, struct, primitive)

This question is not a duplicate of this question. As I wrote in the comment, I do not have to use ==. It is just one of the ways I have tried

Community
  • 1
  • 1
Nuri Tasdemir
  • 9,720
  • 3
  • 42
  • 67
  • 1
    There is already [`Object.Equals`](https://msdn.microsoft.com/en-us/library/bsc2ak47(v=vs.110).aspx) which does the same – Tim Schmelter Aug 05 '16 at 15:03
  • 1
    You can use `t1.Equals(t2)` with some null checks. – Zein Makki Aug 05 '16 at 15:04
  • 1
    there is no use of creating this in my point of view – Ehsan Sajjad Aug 05 '16 at 15:05
  • @FrankerZ I don't have to use ==. So this is a different question – Nuri Tasdemir Aug 05 '16 at 15:06
  • @EhsanSajjad Where I am going to use this code is not a part of the question. Is that a necessity for an answer? As I said to FrankerZ in previous comment, == is one of the ways I am using. What I ask may be achieved trough other means. IMHO this is not a duplicate (at least) of that question. Could you give me you reasons why it is a duplicate. Thanks – Nuri Tasdemir Aug 05 '16 at 15:15
  • well let others also decide, if it is not duplicate, it will get reopened – Ehsan Sajjad Aug 05 '16 at 15:18

0 Answers0