73

Now I have two classes allmethods.cs and caller.cs.

I have some methods in class allmethods.cs. I want to write code in caller.cs in order to call a certain method in the allmethods class.

Example on code:

public class allmethods
public static void Method1()
{
    // Method1
}

public static void Method2()
{
    // Method2
}

class caller
{
    public static void Main(string[] args)
    {
        // I want to write a code here to call Method2 for example from allmethods Class
    }
}

How can I achieve that?

Mark Benningfield
  • 2,800
  • 9
  • 31
  • 31
Mina Hafzalla
  • 2,681
  • 9
  • 30
  • 44

1 Answers1

128

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • 2
    I do appreciate this answer a lot, it is such a hard thing for newbs like myself to get their heads around +1. – Neil Meyer Oct 31 '18 at 10:18
  • This is great! thank you. But how can I execute these methods without using the className before each time I call the function? I have seen somebody do that. – SJ10 Jul 30 '19 at 23:54
  • 1
    @SJ10 I think you're referring to the (relatively) new `using static` directive. See my updated answer. – p.s.w.g Jul 31 '19 at 16:10
  • @p.s.w.g Ah yes, thank you! this clears up some confusion of the code I have been reading. – SJ10 Aug 01 '19 at 19:40