Possible Duplicate:
Why C# is not allowing non-member functions like C++
Instead of writing StaticClass.Function() I'd like to simply write Function(). There will be many functions and all should be accessible from different (and unrelated) classes and files. How do I put these functions in a specific namespace? Simply declaring it there will give me a compile error
error CS1518: Expected class, delegate, enum, interface, or struct
I know other .NET languages can do it. Is there a compile option i may use? Perhaps even undocumented?
C# does not allow for free functons. Each function must reside in a type. This is just the way it works, it's not a matter of technical possibility, it was a design decision.
You may be interested in this article.
On a side note, ever notice how Intellisense works much, much better when writing C# than C++? This is one of those things that help (not the only one, but one).
EDIT: Funny, in reading that linked article I noticed that this is a dup...
C# does not allow this, by design.
However, if your goal is merely to reduce typing, you have a couple of options.
First, you can use the using Directive to simplify this. By adding this:
using SC = YourNamespace.StaticClass;
You can shorten the calls within that specific document to:
SC.Function();
Another option which is occasionally appropriate would be to use an Extension method. This can eliminate the need to specify the type, as the function appears to be a member function of the first argument. Of course, this wouldn't work for the supplied example (as it requires a parameter), but is potentially another option to reduce the amount of typing and searching, depending on the specific use case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With