Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify to validate this situation with generics?

Tags:

c#

generics

I'm trying to validate this class: min >= max. I realized using generics I can't use the comparators.

This is my generic 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 datatype can be only numbers, is there a way to accept just numbers and accept the <=?

like image 937
Darf Zon Avatar asked Dec 16 '22 02:12

Darf Zon


2 Answers

No, you can't constrain generics to numbers, but you can constrain 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 validation exception or whatever validation you'd like. You can use the same thing to make sure value is >= min and <= max.

if (value.CompareTo(min) >= 0 && value.CompareTo(max) <= 0)...
like image 177
James Michael Hare Avatar answered Jan 05 '23 12:01

James Michael Hare


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

    public bool Check(T value)
    {
        return value.CompareTo(min) >= 0 && value.CompareTo(max) <= 0;
    }
}

If you range between 0 and 10, and want 0, 10 to fail (exclude min and max) - simply replace ">=" with ">" and "<=" with "<".

I would also recommend changing in the Equals override from:

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

to this:

return this.MinValue.CompareTo(other.MinValue) == 0 &&
       this.MaxValue.CompareTo(other.MaxValue) == 0;
like image 24
SimpleVar Avatar answered Jan 05 '23 12:01

SimpleVar