tags:

views:

1010

answers:

6

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?

+1  A: 

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

nos
+3  A: 

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

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.

Jesse C. Slicer
A: 

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.

Nader Shirazie
+1  A: 

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();
    }
}
Michael Valenty
Thanks a lot! You saved my day
djzmo
A: 

thanks, this helped out...

me