Generic InBetween Function.
Posted
by
Luiscencio
on Stack Overflow
See other posts from Stack Overflow
or by Luiscencio
Published on 2011-01-14T17:50:38Z
Indexed on
2011/01/14
19:54 UTC
Read the original article
Hit count: 276
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
© Stack Overflow or respective owner