user1133341
user1133341

Reputation: 35

How to use instance class in C# console app

Trying understand c# console app, static make me crazy.

In my app:

static void Main(string[] args) {TimerCallback callback...}
static void Tick(Object state) { !here the problem! }
class myclass { all app logic }

Problem is, in Tick method i need use instance of myclass, but i cant create new instance like:

 myclass mc = new myclass();
 static void Tick(){}...

"An object reference is required for the non-static field, method, or property". It works if i put myclass inside of Tick, but timer will be always create new instance of myclass, and all data in the class will dissapear.

P.S. sorry my english.

Upvotes: 1

Views: 5132

Answers (1)

Tim S.
Tim S.

Reputation: 56536

You might want something like this:

static MyClass myClass;
static void Main(string[] args) { myClass = new MyClass(); TimerCallback callback... }
static void Tick(Object state) { myClass.DoSomething(); }
class MyClass { all app logic }

That is, create a static field that will contain an instance of MyClass, and use that in your static methods.

Upvotes: 3

Related Questions