Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic InBetween Function

Tags:

c#

generics

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

like image 654
Luiscencio Avatar asked Jan 20 '23 17:01

Luiscencio


2 Answers

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;
}
like image 136
Yuriy Faktorovich Avatar answered Jan 28 '23 05:01

Yuriy Faktorovich


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);
like image 30
Mark H Avatar answered Jan 28 '23 04:01

Mark H