Is there a way to call a static function, not to mention the type?

A simple question, I do not think it is possible, but were surprised before.

I have a library with all kinds of mathematical functions, let's look at a very simple example of flooring:

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 would just type

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

But this does not work, because it is not declared in this class, it is in the library. It makes me type

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

which adds noise to the code. I could cut it to

 using m = MyMathLibrary.MathLib; .. yadayada var mat_adjusted = m.floorcap(1, maturity, 5); 

but still, I would rather not type the class name all the time. Is it possible? I write code in F # too, and you seem to be used to the fact that you do not need to specify a type / module, etc. Over time. When I have to write C #, this thing annoys me (a little), because it distracts from the actual "meat stuff".

There are many functions here when you need to call several functions nested, etc. all these points and class names add up. I like my code as clean as possible.

Thanks in advance,

Geert Yang

+4
source share
5 answers

No, this is not possible - it must be qualified depending on where it is (obviously, if the thing is within your current context, then you could, but this does not correspond to the point of the question and purpose.)

This is because nothing directly lives above any types, etc., so there is no sense in a โ€œglobal challengeโ€, so to speak.

+5
source

One way to do this is to do an extension method instead. For example, 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 as follows:

 var mat_adjusted = maturity.floorcap(1, 5); 
+3
source

If you want to save while typing, you can copy and paste method stubs into each of your client classes.

 private static double floorcap(double floor, double value, double cap) { return MathLib.floorcap(floor, value, cap); } 
+1
source

The only way that can give you something like what you want is to use extension methods to expand the types of arithmetic operations that you want to use:

 public static class MathLibExt { public static double FloorCap(this double value, double floor, double cap) { return Math.Min(Math.Max(floor, value), cap); } } // call like var value = 25.0; var capped = value.FloorCap(1, 10); 
0
source

There are ways to do this, for example, by defining a private static method in each class that calls your library; however, I would say that the best solution is to simply overcome it and give the class name every time.

0
source

All Articles