If I want to make a function that can be called from every location in my project, I create static class with a static function, but I still have to refer to the function as Class.Method
instead of Method
even if I import the static class with using
. How can you do this?
Asked
Active
Viewed 566 times
0

Maestro
- 9,046
- 15
- 83
- 116
-
3My question is... _why?_ – Dave Zych Mar 31 '14 at 20:38
-
2Ask yourself: how many times have I *consumed* such a feature in C#? The answer is zero. This should tell you something. – Marc Gravell Mar 31 '14 at 20:38
-
@DaveZych .NET creators decided to go different way than Java creators. – Ulugbek Umirov Mar 31 '14 at 20:39
-
@UlugbekUmirov This cannot be done in `Java` either. Methods in Java must be contained within a type. – Servy Mar 31 '14 at 20:39
-
there are many obscure features of all languages. a significant perentage of SO traffic is about obscure features – pm100 Mar 31 '14 at 20:39
-
@Servy In Java you can import static function from class. So you don't need to prefix the method with class name. – Ulugbek Umirov Mar 31 '14 at 20:40
-
Use VB modules if you want this feature. – Olivier Jacot-Descombes Mar 31 '14 at 20:40
-
@DaveZych Im porting a Java library to C# and I want the resulting code to look as much as possible as the original, because it will make it easier to sync changes in the future. – Maestro Mar 31 '14 at 20:45
-
@Muis - mirror is two way street :)... consider to change original to match features. – Alexei Levenkov Mar 31 '14 at 21:21
4 Answers
6
You cannot. Functions must be declared within a type in C#.

Servy
- 202,030
- 26
- 332
- 449
-
There are no functions in C# actually, they are methods - that's why they need to be inside a type – Michał Mar 31 '14 at 20:45
2
At the Build 2014 keynote it was announce that the following should work in the next version:
using Class;
...
Method(...);
Basically, exactly what you wanted. The using Class;
imports the static methods from the Class
type so that they don't need to be referenced from the type.

Marc Gravell
- 1,026,079
- 266
- 2,566
- 2,900
0
You have to refer to the STATIC method as Class.Method() unless you are inside the class.

T McKeown
- 12,971
- 1
- 25
- 32
0
First of all - you cannot import a static class. You only import a namespace
in which it is contained.
You actually cannot do it - that is the basic principle of OOP - everything has it's class. Methods in static class
es are the replacement for the global functions in C++

Michał
- 2,202
- 2
- 17
- 33