7

I have the following generic math function:

private static T Fade<T>(T t)
    where T : IFloatingPoint<T>
{
    return t * t * t * (t * (t * 6 - 15) + 10);
}

This doesn't compile however, since 6, 15 and 10 are not of type T.

The best solution I could come up with was to define a static class like this:

private static class GenericValues<T>
    where T : IFloatingPoint<T>
{
    public static readonly T Two = T.One + T.One;
    public static readonly T Three = Two + T.One;
    public static readonly T Four = Three + T.One;
    public static readonly T Five = Four + T.One;

    public static readonly T Six = Five + T.One;
    public static readonly T Ten = Five * Two;
    public static readonly T Fifteen = Five * Three;
}

And then the function becomes this:

private static T Fade<T>(T t)
    where T : IFloatingPoint<T>
{
    return t * t * t * (t * (t * GenericValues<T>.Six - GenericValues<T>.Fifteen) + GenericValues<T>.Ten);
}

This feels a bit like a hack though, is there a nicer way to do this?

Rick de Water
  • 2,388
  • 3
  • 19
  • 37

1 Answers1

9

You can use one of the INumberBase<T>.CreateX methods, for example INumberBase<TSelf>.CreateChecked<TOther>(TOther) to convert the number literals to the generic number type:

private static T Fade<T>(T t)
    where T : IFloatingPoint<T>
{
    return t * t * t * 
        (t * (t * T.CreateChecked(6) - T.CreateChecked(15)) + T.CreateChecked(10));
}
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • 1
    Given that I had to also do `T two = T.One + T.One` etc, this would make my life easier too. Never knew about `T.Create()` methods. – John Alexiou Feb 06 '23 at 22:52