JFallz JFallz - 2 months ago 7
C# Question

How to make method call another one in classes C#?

Now I have two classes

AllMethods.cs
and
caller.cs
.

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

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? Any Help?

Thanks.

Answer

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

Further Reading

Comments