2

Hi is it possible that the following method somehow recognizes that it can be only int, double, decimal or float and add them with the + operator. If I use dynamic then it is a problem because I wish to compare the time for addition for the different types and if they are cast to dynamic I do not know what will be the effect. Thanks.

    public static void Addition<T>(T number) where T:int, double, decimal, float            
    {
    //calculate elapsed time for operation
     var x=  number + number;// cannot add T + T
    }
Petar Drianov
  • 120
  • 2
  • 13
  • Your generic type constraint says that T has to be all of those types. Not any of them. The easiest way if you want to test, would be to create 4 different overloads of the Addition() method; one for each type. – itsme86 Jun 02 '14 at 19:40
  • 1
    Go with dynamic... The first time you use the method with specific types, it will take longer to compile. However, thereafter, it will be quite quick (consistently). So simply ignore the time taken for the first call and average out the remainder. You can work out the time between a pure method and a dynamic (compiled) method too. – Meirion Hughes Jun 02 '14 at 19:49
  • @MeirionHughes The use of `dynamic` here isn't about compile speed. It's not even about runtime speed for that matter. It means losing static type safety. You cease to be notified at compile time if you are calling the method with a variable that isn't a valid type. That's a *big* deal with it comes to writing maintainable programs. – Servy Jun 02 '14 at 20:24

1 Answers1

3

The only way to constraint a parameter to be one of a finite set of types known at compile time is to create an overload for each of those types. In this case that means having an overload for int,double,decimal, and float.

There is no way to constraint a generic argument to one in which a given operator overload exists for that type.

Servy
  • 202,030
  • 26
  • 332
  • 449