Ators Ators - 3 months ago 7
C# Question

Calling non static method from static method USING instance created in the static method

i try to write my own Console Snake game, the problem is this..
I have my whole game in main thread, then I created addVlakno (new thread) to count seconds there, so it can every second call an method from instance of hra created in Main, so it will Clear console and do some methods to be moved.

class Program
{
static void Main(string[] args)
{
Hra hra = new Hra();
Thread addVlakno = new Thread(Run);
addVlakno.Start();

...

}

public static void Run()
{

Thread.Sleep(1000);
hra.method(); // The problem is here*

}
}


*I know i have to have an existing instance of Hra here, but i need to use the instance created in Main, is is possible? By some delegates, or some pointers or ather way? Because the created hra has all the values for the game, i need to use them.

I tried to put
Hra hra = new Hra();
before Main, but in this case, i couldn't use it even in the main.

Answer

You can pass arguments as follows:

static void Main(string[] args)
{
    Hra hra = new Hra();
    Thread addVlakno = new Thread(()=>Run(hra));
    addVlakno.Start();
}

public static void Run(Hra hra)
{
    Thread.Sleep(1000);
    hra.method(); // No problem here* 
}