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

4 Answers 4

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();
}
Sign up to request clarification or add additional context in comments.

Comments

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();

3 Comments

Is there a way to call "HelperMethod()" without the helperclass?
There is not. Methods must be contained within a class or struct.
If you declare using static HelperClass you can call HelperMethod()
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.

Comments

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

2 Comments

I am not able to access MyMethod without calling 'Extensions.MyMethod()' within my Form_load of another class. THanks anyway.
This seemed really cool until I remembered that the Main function in C# is required to be static.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.