Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I multiply a float and a generic type?

Tags:

c#

generics

mono

I'm programming in Unity 3.4.2 on OS X using C#.

I have a class like the following:

class Foo<T>
{
    public T DoFoo(T bar)
    {
        float aFloatValue = 1.0f;
        // Do other stuff...
        return aFloatValue * bar;
    }
}

When Unity compiles this class, it gives me this error message:

error CS0019: Operator *' cannot be applied to operands of type float' and `T'

I know that the types I provide for T will support multiplication with float. How can I implement generic multiplication in this case?

like image 540
Troy J. Farrell Avatar asked Feb 28 '12 16:02

Troy J. Farrell


People also ask

Can I multiply double with float?

You can add, subtract, multiply, and divide double and float variables the same as you can with doubles and ints. The result will again be a double type.

Is it possible to inherit from a generic type?

An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.

Where is generic method?

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.


2 Answers

In C# 4, you can use dynamic if you are confident that float * T => T.

class Foo<T>
{
    public T DoFoo(T bar)
    {
        dynamic aFloatValue = 1.0f;
        // Do other stuff...
        return aFloatValue * bar;
    }
}

Other options are:

  1. Use an expression-tree and compile it down to delegate (suitable for caching) that does the multiplication for you.
  2. Reflection - Either directly, or by producing a delegate first.
  3. Accept a delegate, as JaredPar mentions.
like image 53
Ani Avatar answered Sep 16 '22 17:09

Ani


Ahhh, good ol' Haskell.

You can't do that in C#, you should have multiple DoFoo's, one for float, one for double and one for decimal - there aren't all that many float types. You can drop the float variant, too, as it will be implicitly cast into a double anyway.

like image 20
zmbq Avatar answered Sep 20 '22 17:09

zmbq