Yana D. Nugraha
Yana D. Nugraha

Reputation: 5299

Is it possible to call a non-static function inside static function in C#?

Is it possible to call a non-static function that uses a public non-static class inside a static function in C#?

public class MyProgram
{
    private Thread thd = new Thread(myStaticFunction);
    public AnotherClass myAnotherClass = new AnotherClass();

    public MyProgram()
    {
        thd.Start();
    }

    public static void myStaticFunction()
    {
        myNonStaticFunction();
    }

    private void myNonStaticFunction()
    {
        myAnotherClass.DoSomethingGood();
    }
}

Well, the invalid code like above is what I need.

Any idea?

Upvotes: 2

Views: 6130

Answers (5)

Mike Valenty
Mike Valenty

Reputation: 8981

It sounds like you want to pass data to your thread. Try this:

public class MyProgram
{
    private Thread thd;
    public AnotherClass myAnotherClass = new AnotherClass();

    public MyProgram()
    {
        thd = new Thread(() => myStaticFunction(this));
        thd.Start();
    }

    public static void myStaticFunction(MyProgram instance)
    {
        instance.myNonStaticFunction();
    }

    private void myNonStaticFunction()
    {
        myAnotherClass.DoSomethingGood();
    }
}

Upvotes: 1

Nader Shirazie
Nader Shirazie

Reputation: 10776

If the myAnotherClass variable is declared as static, then yes, you can call methods on it.

That's not quite the answer to the question you asked, but it will allow you to call the method in the way you wantt to.

Upvotes: 0

Jesse C. Slicer
Jesse C. Slicer

Reputation: 20157

No.

Non-static functions, by definition, require a class instance. If you create an instance of your class within the static function, or have a static Instance property in your class, you can via that object reference.

Upvotes: 0

JaredPar
JaredPar

Reputation: 754545

Not directly no. You must have an instance of Program in order to call the non-static method. For example

public static void MyStaticFunc(Program p) {
  p.myNonStaticFunction();
}

Upvotes: 3

nos
nos

Reputation: 229058

To call a non static function you need to have an instance of the class the function belongs to, seems like you need to rethink why you need a static function to call a non static one. Maybe you're looking for the Singleton pattern ?

Or maybe you should just pass in a non-static function to new Thread()

Upvotes: 1

Related Questions