c# – What are some useful examples of extension methods dealing with mathematics and calculations? – Education Career Blog

My very often used extension method is

public static double Pi(double this x) { return Math.PI*x; }

in order to have access to 2.0.Pi() or 0.5.Pi() .. etc

What are some other examples of mathematics related extension methods the people use often?

PS. Just curious.

,

public static double Squared(double this x) { return x*x; }

,

In order to get the creative juices flowing I will offer some more examples…

public static double Raise(double this x, double exponent)
{
    return Math.Pow(x, exponent);
}

public static bool NearZero(double this x, double tolerance)
{
     return Math.Abs(x) <= tolerance;
}

public static double Cap(double this x, double threshold)
{
    return Math.Abs(x)<threshold ? x : threshold*Math.Sign(x);
}

public static double SignOf(double this x, double sense)
{
    return Math.Sign(sense)*Math.Abs(x);
}

public static double ToRadians(double this x) { return Math.PI*x/180; }
public static double ToDegrees(double this x) { return 180*x/Math.PI; }

PS. Thanks @Aaron for posting extensionmethods.net. Unfortunately they have little in terms of math related postings.

Leave a Comment