2

Here is my code:

public class Range<TNum> where TNum : IComparable
{
    public TNum From { get; set; }
    public TNum To { get; set; }
}

public class MarkableRange<TNum> where TNum : IComparable
{
    private readonly List<Range<TNum>> _markedRanges = new List<Range<TNum>>();

    public void MarkOne(TNum number)
    {
        _markedRanges.Where(r => number >= r.From && number <= r.To);
    }
}

compiler says that it cannot apply operator >= on operands in number >= r.From and number <= r.To

I could get away with List<Tuple<TNum, TNum>> but i wanted something more meaningful. So is it me who did something wrong or c# compiler not that smart to understand my intention?

Andrej Slivko
  • 1,236
  • 2
  • 12
  • 27
  • Ups, I probably was too quick about saying that Tuple would work here, looks like i have same issue with Tuple – Andrej Slivko Jul 04 '11 at 15:10
  • See this Skeet answer: http://stackoverflow.com/questions/5101378/problem-comparing-items-implementing-icomparable/5101400#5101400. Also I suggest using `IComparable` instead if just `IComparable` – sehe Jul 04 '11 at 15:14

2 Answers2

7

TNum is constrained to implement IComparable, which doesn't have the operators you're using (<= and >=). You should use the CompareTo method instead:

public void MarkOne(TNum number) {
  _markedRanges.Where(r => number.CompareTo(r.From) >= 0 && number.CompareTo(r.To) <= 0);
}

To use the operators, take a look here.

Also, prefer the generic IComparable<T>.

Jordão
  • 55,340
  • 13
  • 112
  • 144
  • Ok, that one threw me, I could have sworn those operators were overloaded for `IComparable`. – Flynn1179 Jul 04 '11 at 15:09
  • 1
    Unfortunately the operator overloading cannot be expressed on an interface. – vcsjones Jul 04 '11 at 15:10
  • Yeah, now I think about it, I'm thinking of the FxCop warning about overloading operators on anything that IMPLEMENTS it, not the interface itself. (http://msdn.microsoft.com/en-us/library/ms182163%28v=vs.80%29.aspx). – Flynn1179 Jul 04 '11 at 15:19
  • It's very mechanical and a lot of boilerplate code to follow that rule on all types that implement `IComparable`. I'd favor a different [strategy](http://codecrafter.blogspot.com/2010/04/more-understandable-icomparable.html). – Jordão Jul 04 '11 at 15:21
0

You can overload operators in C#, so you could define the >= and <= operators on your Range class that delegates to the IComparable implementation. Should work then.

MrKWatkins
  • 2,621
  • 1
  • 21
  • 34