Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to call a non-static method from a static method?

Here's what I have.

public static void Person_home_phone_TextChanged(object sender, EventArgs e) { ... }

Is there any way to access non-static methods from the same or another class from inside this static method?

I need grab the text in the Person_home_phone text box and save it to a class data member.

like image 393
Glimpse Avatar asked Apr 09 '13 14:04

Glimpse


3 Answers

Example() -> Example

You would just need to create an instance of the type then call the non-static, from a static method.

public class Example(){

    public static void StaticExample()
    {

        Example example = new Example();
        example.NonStatic();
    }

    public void NonStatic()
    {

    }

}
like image 166
Gabe Avatar answered Nov 15 '22 09:11

Gabe


You need to have a instance of the class to call a non-static method.

like image 25
Mattias Jakobsson Avatar answered Nov 15 '22 09:11

Mattias Jakobsson


Solution #1: Instantiate a new instance of Car every time the method is called.

 public static void DoSomething()
        {
            Car c = new Car();
            c.NonStaticMethod();
        }

Solution #2: Pass a Car to the method.

 public static void DoSomething(Car c)
        {
            c.NonStaticMethod();
        }

Solution #3:

Use a singleton Car to support the static method. (If calls from multiple threads are a possibility, you might also need locking. Note that System.Windows.Forms.Timer does not introduce a thread.)

 public class Car
    {
        private static Car m_Singleton = new Car();

        public static void DoSomething()
        {
            m_Singleton.NonStaticMethod();
        } 

Note that you have not explained your memory problems with Timer. It is very possible that there is a solution to that underlying problem.

like image 45
Kiran.Bakwad Avatar answered Nov 15 '22 07:11

Kiran.Bakwad