Search code examples
c#usingreadabilitysimplify

How to avoid "Math." in front of every math function in C#?


I'm writing some C# heavy in mathematics. Many lines in sequence using plenty of abs(), min(), max(), sqrt(), etc. Using C# is the plain normal way, I must preface each function with "Math." For example

double x = Math.Min(1+Math.Sqrt(A+Math.Max(B1,B2)),
           Math.Min(Math.Cos(Z1),Math.Cos(Z2)));

I'd rather write code like in C:

double x = min(1+sqrt(A+max(B1,B2)), min(cos(Z1), cos(Z2)));

This is easier to read and looks more natural to scientists and engineers. The normal C# way hides the good bits in a fog of "Math."

Is there a way in C# to do this?

After some googling I found an example which lead me to try

using min = Math.Min;
...
double x = min(a,b);        

but the "using" statement produced an error, "System.Math.Min(decimal,decimal) is a method but is used like a type" but otherwise this looked like a good solution. (What is 'decimal', anyway?)


Solution

  • One of many solutions would be to define delegates locally. The code

    double x = Math.Min(1+Math.Sqrt(A+Math.Max(B1,B2)),
               Math.Min(Math.Cos(Z1),Math.Cos(Z2)));
    

    could be rewritten to the following implementation.

    Func<double,double,double> min = Math.Min;
    Func<double,double,double> max = Math.Max;
    Func<double,double> sqrt = Math.Sqrt;
    Func<double,double> cos = Math.Cos;
    double x = min(1+sqrt(A+max(B1,B2)), min(cos(Z1), cos(Z2)));