Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I properly write Math extension methods for int, double, float, etc.?

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!

like image 930
Mark Carpenter Avatar asked Jun 07 '09 02:06

Mark Carpenter


People also ask

What is correct extension method?

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.

What are extension methods explain with an example?

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.

Which is the correct way to define an extension method Square for int type?

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.


3 Answers

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.

like image 85
jerryjvl Avatar answered Oct 03 '22 12:10

jerryjvl


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

like image 27
Woot4Moo Avatar answered Oct 03 '22 12:10

Woot4Moo


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);
}
like image 32
user168345 Avatar answered Oct 03 '22 12:10

user168345