Alex Rivera | Logout

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

Asked 2009-06-07T02:09:19.143
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!

Edit
Report

1 Answer

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

answered 2009-06-07T02:23:00.037

Your Answer