2

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?

5 Answers 5

3

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();
}
Sign up to request clarification or add additional context in comments.

Comments

1

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();
    }
}

Comments

1

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()

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.