Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to call a static function without having to mention the type?

Tags:

c#

Simple question, I don't think it's possible but have been surprised before.

I have a library with all kind of math functions, lets take a very simple example floorcap:

class MathLib {
    public static double floorcap(double floor, double value, double cap) {
        return Math.Min(Math.Max(floor, value), cap);
    }
}

In another method in another class, I'd like to just type

var mat_adjusted = floorcap(1, maturity, 5);

But that doesn't work, because it's not declared in this class, it's in a library. It makes me type

var mat_adjusted = MathLib.floorcap(1, maturity, 5);

wich adds noise to the code. I could shorten it to

using m = MyMathLibrary.MathLib;

.. yadayada

var mat_adjusted = m.floorcap(1, maturity, 5);

but still, I'd prefer not to have to type the class name all the time. Is that possible? I write code in F# too and you kinda get used to not having to spell out the type/module etc after a while. When I have to write C# this thing annoys me (a little) because it distracts from the actaul 'meat of the thing'.

There are a lot of functions here, when you need to call a few functions nested etc all these dots and class names add up. I like my code as clean as possible.

Thanks in advance,

Gert-Jan

like image 378
gjvdkamp Avatar asked Jan 18 '23 18:01

gjvdkamp


2 Answers

No, this isn't possible - it has to be qualified to the extent of where it resides (obviously if the thing resides within scope of your current context, then you could, but that misses the point of the question and objective.)

This is because nothing directly lives higher than any types etc, - so there is no sense of a "global call", so to speak.

like image 191
Grant Thomas Avatar answered Feb 07 '23 18:02

Grant Thomas


One way to do this would be to make an extension method instead. For instance, if you define your example function in a static class:

static class MathLib
{
    public static double floorcap(this double value, double floor, double cap)
    {
        return Math.Min(Math.Max(floor, value), cap);
    }
}

Then you can use it like this:

var mat_adjusted = maturity.floorcap(1, 5);
like image 21
InvisibleBacon Avatar answered Feb 07 '23 17:02

InvisibleBacon