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

2

5

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)?

Graves answered 18/2, 2012 at 12:50 Comment(0)
S
8

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.

Sarcoid answered 18/2, 2012 at 15:55 Comment(3)
I never really thought about it like that. I guess it was because I started off with the generic version, then copied/pasted it and attempted to just do a quick change.Graves
Also, will this default to select the IComparable<T> option first, and the IComparable option second?Graves
@m-y: Overload resolution will choose the more specific method. If there's no way to determine which one is more specific then you'll get an ambiguity error.Sarcoid
C
3

In .NET method resolution overload doesn't take into account return types and generic constraints. So even if IComparable and IComparable<T> had something in common that would still not work. Just pick the IComparable<T> version. Standard .NET types such as Int32, Decimal, DateTime, ... implement both interfaces anyway.

Cashbox answered 18/2, 2012 at 13:2 Comment(1)
That's what I figured, but I wanted to make sure I wasn't missing something here. I will end up going with the generic version. I was just hoping to have my method be available for other code that implements only IComparable and not both (or just IComparable<T>).Graves

© 2022 - 2024 — McMap. All rights reserved.