How to compare two generic types?

Viewed 3789

I make my class generic.The T - can be string or int.

I have this feature class:

public class Feature<T>// : IComparable
{
    public T CurrentFeatureCode { get; set; }

    public T StreetCode1 { get; set; }
    public T BuildingNumber1 { get; set; }
    public string BuildingLetter1 { get; set; }

    public T StreetCode2 { get; set; }
    public T BuildingNumber2 { get; set; }
    public string BuildingLetter2 { get; set; }

    public double CoordinateX { get; set; }
    public double CoordinateY { get; set; }

    public string Filter { get; set; }

    public string ToString(T streetCode)
    {
        return StreetCode2 == streetCode ? String.Format("{0}{1}", BuildingNumber2, BuildingLetter2) : String.Format("{0}{1}", BuildingNumber1, BuildingLetter1);
    }
}

As you can see I have ToString method inside Feature class that compares two values:

StreetCode2 == streetCode ? String.Format("{0}{1}", BuildingNumber2, BuildingLetter2) : String.Format("{0}{1}", BuildingNumber1, BuildingLetter1);

I get error on this row:

Error   11  Operator '==' cannot be applied to operands of type 'T' and 'T' .

My question is how can I compare two values of T type?

3 Answers

For your type T, implement the IEquatable<T> interface. Override the Equals() method with logic that suits your case. Note that you must override GetHashCode() as well.

If you are happy with the default comparer, then you can do this:

public class Feature<T>// : IComparable
{
    public T StreetCode2 { get; set; }
    public string ToString(T streetCode)
    {
        if (EqualityComparer<T>.Default.Equals(StreetCode2, streetCode))
        {
            return "Equal";
        }

        return "Not Equal";
    }
}

And here is a test:

var feature1 = new Feature<string>();
feature1.StreetCode2 = "two";
string equals = feature1.ToString("two");

I believe the recommended approach would be to use the IEquatable interface with generics and the Equals() method, but I am not sure if that suits your tastes.

Related