9

I want to write a series of Extension methods to simplify math operations. For example:

Instead of

Math.Pow(2, 5)

I'd like to be able to write

2.Power(5) 

which is (in my mind) clearer.

The problem is: how do I deal with the different numeric types when writing Extension Methods? Do I need to write an Extension Method for each type:

public static double Power(this double number, double power) {
    return Math.Pow(number, power);
}
public static double Power(this int number, double power) {
    return Math.Pow(number, power);
}
public static double Power(this float number, double power) {
    return Math.Pow(number, power);
}

Or is there a trick to allow a single Extension Method work for any numeric type?

Thanks!

Mark Carpenter
  • 17,445
  • 22
  • 96
  • 149
  • +1 Yeah, I'm surprised that wasn't part of the framework to begin with. – Mark Carpenter Jun 07 '09 at 14:16
  • 1
    **Caveat** when using such extension methods: **`-10.Power(2) == -100`**. The minus sign get applied to the result of `10.Power(2)`. – HugoRune Feb 24 '17 at 09:40
  • @HugoRune: Interesting point! But I do think that the OP would still be using variables rather than explicit values. The hardcoded values in the question seem to be a matter of example rather than intended usage. – Flater Sep 29 '17 at 15:15

4 Answers4

2

Unfortunately I think you are stuck with the three implementations. The only way to get multiple typed methods out of a single definition is using generics, but it is not possible to write a generic method that can do something useful specifically for numeric types.

jerryjvl
  • 19,723
  • 7
  • 40
  • 55
1

You only need to override Decimal and Double as is noted in this question: here

Community
  • 1
  • 1
Woot4Moo
  • 23,987
  • 16
  • 94
  • 151
1

One solution I use is to make the extension on object. This makes this possible, but unfortunately it will be visible on all objects.

public static double Power(this object number, double power) 
{
    return Math.Pow((double) number, power);
}
user168345
  • 167
  • 2
  • 8
0

I dont think its possible with C# 3.0. Looks like you might be able to do it C# 4.0

http://blogs.msdn.com/lucabol/archive/2009/02/05/simulating-inumeric-with-dynamic-in-c-4-0.aspx

Vasu Balakrishnan
  • 1,751
  • 10
  • 15
  • 1
    Good point... I'm not sure that the performance hit is going to be worth the price in the general case though. – jerryjvl Jun 07 '09 at 02:25
  • the linked artikle does not use dynamic as it was designed, trading type safety for comfort is not the right way i think – quadroid Mar 31 '14 at 07:19