I am tired of writing x > min && x < max
so i wawnt to write a simple function but I am not sure if I am doing it right... actually I am not cuz I get an error:
bool inBetween<T>(T x, T min, T max) where T:IComparable
{
return (x > min && x < max);
}
errors:
Operator '>' cannot be applied to operands of type 'T' and 'T'
Operator '<' cannot be applied to operands of type 'T' and 'T'
may I have a bad understanding of the where
part in the function declaring
note: for those who are going to tell me that I will be writing more code than before... think on readability =) any help will be appreciated
EDIT
deleted cuz it was resolved =)
ANOTHER EDIT
so after some headache I came out with this (ummm) thing following @Jay Idea of extreme readability:
public static class test
{
public static comparision Between<T>(this T a,T b) where T : IComparable
{
var ttt = new comparision();
ttt.init(a);
ttt.result = a.CompareTo(b) > 0;
return ttt;
}
public static bool And<T>(this comparision state, T c) where T : IComparable
{
return state.a.CompareTo(c) < 0 && state.result;
}
public class comparision
{
public IComparable a;
public bool result;
public void init<T>(T ia) where T : IComparable
{
a = ia;
}
}
}
now you can compare anything with extreme readability =)
what do you think.. I am no performance guru so any tweaks are welcome
IComparable means the object implements a CompareTo method. Use
public static bool InBetween<T>(this T x, T min, T max) where T:IComparable<T>
{
return x.CompareTo(min) > 0 && x.CompareTo(max) < 0;
}
You need to use the .CompareTo
method of your variable and check for < and > 0. (This is why you've constrained T to IComparable).
return (x.CompareTo(min) > 0 && x.CompareTo(max) < 0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With