4

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?

Michael
  • 13,950
  • 57
  • 145
  • 288

3 Answers3

3

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.

Dido
  • 520
  • 2
  • 7
  • 21
3

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");
CodingYoshi
  • 25,467
  • 4
  • 62
  • 64
1

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.

Florin Toader
  • 337
  • 1
  • 9