Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a method from another class

Tags:

c#

I'm wanting to know how I can call a method from another class without having to make a new instance of that class. I've looked up this and 90% of the examples I see require me to make a new copy of my referenced class.

Something like this:

Fooclass test = new Fooclass();
test.CallMethod();

However, I'm wondering if there is a way I can call the method without making a new class instance. Right now I've tried the following in unity.

public ImageLoader image; 
void Start () 
{
    image = gameObject.GetComponent<ImageLoader>() as ImageLoader;
}

void OnClick()
{
    image.MoveForward();
}

however, when I run this I get the following error:

NullReferenceException: Object reference not set to an instance of an object

i know this would be settled with making a new instance of my image loader class but I can't do that as it is holding a lot of data I don't want duplicated multiple times.

like image 505
N0xus Avatar asked Mar 18 '14 10:03

N0xus


People also ask

How do you call a method from another class in Java?

If you want to acess it from another class file then you have to instantiate an Object and then access it using the public method: Main m = new Main(); int a = m. getVariableName(); Hope it helps.

How do you call a method from another class without creating an object?

We can call a static method by using the ClassName. methodName. The best example of the static method is the main() method. It is called without creating the object.

How do you call a method in another?

In order to call Method in another Method that is contained in the same Class is pretty simple. Just call it by its name!


1 Answers

Yes you can. The first way is to make your class to be static.

public static class Fooclass
{
    // I don't know the return type of your CallMethod, so I used the void one.
    public static void CallMethod()
    {

    }
}

This way, whenever to your code you can call the CallMethod() like the following:

Fooclass.CallMethod()

Another apporach it would be to define a static method in your current class, without the class needed to be static, like the following:

public class Fooclass
{
    // I don't know the return type of your CallMethod, so I used the void one.
    public static void CallMethod()
    {

    }
}

Now since all the instances of the Fooclass would share the same method called CallMethod, you can call it like below:

Fooclass.CallMethod()

without again needed to instantiate an object of type Fooclass, despite the fact that now Fooclass isn't a static class now !

For further documentation please take a look to the link Static classes and Static Members.

like image 97
Christos Avatar answered Oct 15 '22 21:10

Christos