Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Methods inside namespace c#

Is there any way to call a function that is inside of a namespace without declaring the class inside c#.

For Example, if I had 2 methods that are the exact same and should be used in all of my C# projects, is there any way to just take those functions and make it into a dll and just say 'Using myTwoMethods' on top and start using the methods without declaring the class?

Right now, I do: MyClass.MyMethod();

I want to do: MyMethod();

Thanks, Rohit

like image 220
rkrishnan2012 Avatar asked May 12 '12 23:05

rkrishnan2012


4 Answers

You can't declare methods outside of a class, but you can do this using a static helper class in a Class Library Project.

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

Usage (after adding a reference to your Class Library).

HelperClass.HelperMethod();
like image 109
David Anderson Avatar answered Sep 17 '22 15:09

David Anderson


Update for 2015: No you cannot create "free functions" in C#, but starting with C# 6 you'll be able to call static functions without mentioning the class name. C# 6 will have the "using static" feature allowing this syntax:

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

SomeOtherFile.cs:

using static MyClass;

void SomeMethod() {
    MyMethod();
}
like image 36
Asik Avatar answered Sep 18 '22 15:09

Asik


Depends on what type of method we are talking, you could look into extension methods:

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

This allows you to easily add extra functionality to existing objects.

like image 44
box86rowh Avatar answered Sep 19 '22 15:09

box86rowh


Following on from the suggestion to use extension methods, you could make the method an extension method off of System.Object, from which all classes derive. I would not advocate this, but pertaining to your question this may be an answer.

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

You could now write code like MyMethod(); anywhere you have a using SomeNamespace;, unless you are in a static method (then you would have to do Extensions.MyMethod(null)).

like image 24
StellarEleven Avatar answered Sep 20 '22 15:09

StellarEleven