How can I reference a method from another class without instantiating it?

25,983

Solution 1

When you create your visible form store a references to it in some static property. Then other classes can use that property to run public methods of that class.

// the original form
class MyForm()
{
     // form public method
     public void MyMethod() { ... }
}

// class storing the reference to a form
class MyOtherClass
{     
    public static Form MyForm;

    public void ShowForm()
    {
        MyForm = new MyForm();
        MyForm.Show();
    }
}

// invoke form public method in this class
class YetAnotherClass
{
    public void SomeMethod ()
    {
        MyOtherClass.MyForm.MyMethod();
    }
}

Solution 2

You need to somehow get the instance which is visible. Work out some information path from things that already know about your form (or whatever it is) to your other code. Consider what would happen if there were two visible forms - which one would you want? That should suggest a way forward. If you know for a fact that there'll only ever be one visible instance, you could use a singleton - but I'd strongly suggest that you don't.

Bear in mind that you may not need to know of it by its full type name - if this is crossing layers, you may want to work out some interface including the action in some abstract way.

Share:
25,983
Sergio Tapia
Author by

Sergio Tapia

I'm a 21 year old professional programmer that likes to read about a wide range of things related to programming. Currently, I'm pounding away at ASP.Net MVC2.

Updated on July 09, 2022

Comments

  • Sergio Tapia
    Sergio Tapia almost 2 years

    I don't want to create an object because it won't affect my visible form. How can I call a method so it does its thing in the visible side of things.

    public class foo
    {
       public void SetString(string foo)
       {
           label1.Text = foo;
       }
    }
    

    Inside another class:

    foo X = new foo();
    X.SetString("testlololol");
    

    This will set the label, but VIRTUALLY, I won't be able to see it on my form.

    How can I do the same thing, but on my VISIBLE side of things?

  • Sergio Tapia
    Sergio Tapia over 14 years
    I don't really understand. How do I get something that is visible? :S
  • Jon Skeet
    Jon Skeet over 14 years
    @Papuccino1: Well I assume you've already got something that is visible, right? If not, I don't understand the question. If so, you need to somehow pass that reference to the code that needs it.