Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic constraints -- I'm not sure how to fix this situation with an either/or case

Basically I have the following:

public static bool IsBetween<T>(this T value, T a, T b)
    where T : IComparable
{
    ...
}

public static bool IsBetween<T>(this T value, T a, T b)
    where T : IComparable<T>
{
    ...
}

The problem is I can't do this because you can't have a member with the same signature, even if the constraints are different. But, there is no way to state that the constraint is either IComparable OR IComparable<T>. So, I'm not sure what to do here outside of just picking one and going with it. And, no matter which one I pick I'm losing out on the other because they are separate and don't inherit from each other (which makes sense).

Am I missing something here in that is there a way to accomplish using both, or am I going to have to pick one (probably the generic version)?

like image 626
myermian Avatar asked Feb 18 '12 12:02

myermian


People also ask

Where generic type constraint?

The where clause in a generic definition specifies constraints on the types that are used as arguments for type parameters in a generic type, method, delegate, or local function. Constraints can specify interfaces, base classes, or require a generic type to be a reference, value, or unmanaged type.


1 Answers

I don't understand why the first method is generic at all. Why isn't it just:

public static bool IsBetween(this IComparable value, IComparable left, IComparable right)

What value does making the method generic add? Obviously you're not going to avoid the boxing penalty because the values are going to be boxed when you call CompareTo(object).

Unless you have some compelling reason to make the method generic, don't make it generic. It then has a different signature from the other method, and your problem is solved.

like image 200
Eric Lippert Avatar answered Sep 19 '22 23:09

Eric Lippert