Andrej Slivko
Andrej Slivko

Reputation: 1256

Why C# compiler can't understand generic arguments used in separate classes?

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?

Upvotes: 2

Views: 155

Answers (2)

MrKWatkins
MrKWatkins

Reputation: 2658

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.

Upvotes: 0

Jord&#227;o
Jord&#227;o

Reputation: 56497

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>.

Upvotes: 7

Related Questions