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!
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
An extension method is actually a special kind of static method defined in a static class. To define an extension method, first of all, define a static class. For example, we have created an IntExtensions class under the ExtensionMethods namespace in the following example.
To create an extension method make the method static and pass this keyword with the type you want like this. Below method will calculate square of given integer value. This extension method is created for int type and will return an integer as a return value.
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.
You only need to override Decimal and Double as is noted in this question: here
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With