How to specify to check this situation using generics?

I am trying to check this class: min >= max . I realized, using generics, I can not use comparators.

This is my common class.

 public class Range<T> { public T MinValue { get; set; } public T MaxValue { get; set; } public Range() { } public Range(T min, T max) { this.MinValue = min; this.MaxValue = max; } public override bool Equals(object obj) { if (obj == null) return false; var other = obj as Range<T>; return this.MinValue.Equals(other.MinValue) && this.MaxValue.Equals(other.MaxValue); } public override string ToString() { return string.Format("{0},{1}", this.MinValue, this.MaxValue); } } 

T data type can only be a number, is there a way to accept only numbers and accept <= ?

+4
source share
2 answers

No, you cannot hold back generic numbers for numbers, but you can limit T to IComparable<T> and then use CompareTo()

 public class Range<T> where T : IComparable<T> { .... } 

Then you can say:

 if (min.CompareTo(max) >= 0)... 

And throw a check exception or any other check. You can use the same thing to make sure the value is> = min and <= max.

 if (value.CompareTo(min) >= 0 && value.CompareTo(max) <= 0)... 
+11
source
 public class Range<T> where T : IComparable<T> { ... public bool Check(T value) { return value.CompareTo(min) >= 0 && value.CompareTo(max) <= 0; } } 

If you are in the range from 0 to 10 and want 0, 10 to work (exclude min and max), just replace "> =" with ">" and "<=" with "<".

I would also recommend changing in the equation of equality:

 return this.MinValue.Equals(other.MinValue) && this.MaxValue.Equals(other.MaxValue); 

:

 return this.MinValue.CompareTo(other.MinValue) == 0 && this.MaxValue.CompareTo(other.MaxValue) == 0; 
+1
source

Source: https://habr.com/ru/post/1403999/


All Articles