13

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

rkrishnan2012
  • 368
  • 1
  • 2
  • 13

4 Answers4

34

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();
}
Asik
  • 21,506
  • 6
  • 72
  • 131
20

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();
p13i
  • 7
  • 4
David Anderson
  • 13,558
  • 5
  • 50
  • 76
3

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.

box86rowh
  • 3,415
  • 2
  • 26
  • 37
3

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)).

StellarEleven
  • 556
  • 4
  • 8