Alex Rivera | Logout

How to determine if two generic type values are equal?

Asked 2011-01-09T13:41:21.137
14

Update* I am so sorry... my sample code contained an error which resulted in a lot of answers I didn't understand. In stead of

Console.WriteLine("3. this.Equals   " + (go1.Equals(go2)));

I meant to write

Console.WriteLine("3. this.Equals   " + (go1.Equals(sb2)));

I'm trying to figure out how I can successfully determine if two generic type values are equal to each other. Based on Mark Byers' answer on this question I would think I can just use value.Equals() where value is a generic type. My actual problem is in a LinkedList implementation, but the problem can be shown with this simpler example.

class GenericOjbect<T> {
    public T Value { get; private set; }
    public GenericOjbect(T value) {
        Value = value;
    }
    public bool Equals(T value) {
        return (Value.Equals(value));
    }
}

Now I define an instance of GenericObject<StringBuilder> containing new StringBuilder("StackOverflow"). I would expect to get true if I call Equals(new StringBuilder("StackOverflow") on this GenericObject instance, but I get false.

A sample program showing this:

using System;
using System.Text;

class Program
{
    static void Main()
    {
        var sb1 = new StringBuilder("StackOverflow");
        var sb2 = new StringBuilder("StackOverflow");

        Console.WriteLine("StringBuilder compare");
        Console.WriteLine("1. ==            " + (sb1 == sb2));
        Console.WriteLine("2. Object.Equals " + (Object.Equals(sb1, sb2)));
        Console.WriteLine("3. this.Equals   " + (sb1.Equals(sb2)));

        var go1 = new GenericOjbect<StringBuilder>(sb1);
        var go2 = new GenericOjbect<StringBuilder>(sb2);
Edit
Report

1 Answer

1

You can either implement IEquatable<T>, or implement a comparer class that implements IEqualityComparer<T>.

Make sure that value you check for equality is immutable and is set only at initialization of the class.

Another consideration would be to implement IComparer<T>, when you implement this one, you don't have to worry about the hash-code, and thus, can be implemented for mutable types/fields as well.

Once you'll properly implement IEquatable<T> in your class, your questions will be solved.

Update: Calling return EqualityComparer<T>.Default.Equals(Value, value); would basically return same result since there is no IEqualityComparer<T> implemented...

answered 2011-01-09T13:45:46.797

Your Answer