Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a method from one .cs file class in another .cs files class

Tags:

c#

class

I have 2 .cs files each with a class in it. How do I call a method in a class from Form1.cs in another class inside of Form2.cs?

Looks something like this...

Form1.cs

public partial class Class1 : ClassContainer
{
    public void awesomeMethod()
        {
        }
}

Form2.cs

class Class2 : SomethingChanged
{
    public void decentMethod()
    {
    }
}

I would like to call awesomeMethod() inside of the decentMethod(). Thanks.

like image 627
Garrett Avatar asked Aug 02 '12 13:08

Garrett


People also ask

Can you call a method from another class in C#?

You can also use the instance of the class to call the public methods of other classes from another class. For example, the method FindMax belongs to the NumberManipulator class, and you can call it from another class Test.


1 Answers

You mean, like this?

public void decentMethod()
{
    Class1 instance = new Class1();
    instance.awesomeMethod();
}

You need an instance of the class you want to call the method on.


Or, if you don't need/want to work with an instance, make it the method static:

public partial class Class1 : ClassContainer
{
    public static void awesomeMethod()
    {
    }
}

...

public void decentMethod()
{
    Class1.awesomeMethod();
}
like image 65
sloth Avatar answered Sep 18 '22 17:09

sloth