Methods Inside C # Namespace

Is it possible to call a function inside a namespace without declaring a class inside C #.

For example, if I had two methods that are accurate and should be used in all my C # projects, is there a way to just take these functions and make them in a dll and just say “Using myTwoMethods” on top and start using methods without declaring a class ?

Now I'm doing: MyClass.MyMethod ();

I want to do: MyMethod ();

Thanks Rohit

+7
source share
4 answers

You cannot declare methods outside the class, but you can do this using the static helper class in the class library project.

public static class HelperClass { public static void HelperMethod() { // ... } } 

Usage (after adding a link to your class library).

 HelperClass.HelperMethod(); 
+10
source

Update for 2015: No, you cannot create “free functions” in C #, but starting with C # 6, you can call static functions without mentioning the class name. C # 6 will have a function using static that allows you to use this syntax:

 static class MyClass { public static void MyMethod(); } 

SomeOtherFile.cs:

 using static MyClass; void SomeMethod() { MyMethod(); } 
+21
source

Following the recommendations for using extension methods, you can make a method an extension method from System.Object, from which all classes are derived. I would not defend this, but regarding your question this may be the answer.

 namespace SomeNamespace { public static class Extensions { public static void MyMethod(this System.Object o) { // Do something here. } } } 

Now you can write code like MyMethod(); anywhere where using SomeNamespace; if you are not using a static method (then you will need to do Extensions.MyMethod(null) ).

+4
source

Depending on what type of method we are talking about, you can learn extension methods:

http://msdn.microsoft.com/en-us/library/bb383977.aspx

This allows you to easily add additional features to existing objects.

+2
source

All Articles