0

Basically i have a specific method which uses double and int values to figure out a css class i want to set. I'm doing the same in a different place but with int + int there instead.

That spawned the question whether there is a good way to have a one for all solution.

Overloads would have been one way to do it but i would love to not write an overload for all variations of numbers.

So i thought i'd have a look wether there is a number specific interface type i can use as generic type constraint - but i didn't find one (since anything could implement IConvertible?)

Result of int32 decompile :

#if GENERICS_WORK
public struct Int32 : IComparable, IFormattable, IConvertible
    , IComparable<Int32>, IEquatable<Int32>
/// , IArithmetic<Int32>
#else
public struct Int32 : IComparable, IFormattable, IConvertible
#endif

Nope, no number interface.

This is what i came up with - which works fine, but also accepts calls on potential non number objects. Any suggestions on how to make the method more restrictive?

    public static string GetThresholdColorClass(IConvertible desiredThreshold, IConvertible actualProgress)
    {
        var actual = actualProgress.ToDouble(CultureInfo.InvariantCulture);
        var desired = desiredThreshold.ToDouble(CultureInfo.InvariantCulture);
        if (actual >= desired)
            return "green";
        if (actual <= 0)
            return "red";
        return "yellow";
    }
Dbl
  • 5,634
  • 3
  • 41
  • 66

1 Answers1

2

Sadly there isn't anything (see for example Is there a constraint that restricts my generic method to numeric types?). You can't make a generic class that requires "numbers" as parameters.

What you could do is create only the double variant of the methods (there is an implicit conversion from int to double, and doubles can contain all the int values)

Technically Gravell wrote some functions to do math with generic types... see https://jonskeet.uk/csharp/miscutil/usage/genericoperators.html , but they are a little "hack"ey :-)

tukaef
  • 9,074
  • 4
  • 29
  • 45
xanatos
  • 109,618
  • 12
  • 197
  • 280
  • meh. shame there is no built in way. however implicit casting does the job too here. Also thanks for the reference to that other question. Kind of makes mine a duplicate. Didn't find it while searching though - slightly different words. Now i'll have to look up the T4 solution because that looks rather interesting as well. haha. Thank you! – Dbl Feb 19 '15 at 14:48
  • @AndreasMüller If you want to test the generic "hack", here there are some lines of code I wrote some years ago http://stackoverflow.com/a/18190731/613130 . You can easily repurpose them for the other operators. – xanatos Feb 19 '15 at 14:50