C #: (static) Class Level Variables

This is definitely a bit of a noob question, but my searches from so far have not cleared the issue for me.

A particular console application is required to store several class level variables. In one case, I want to keep a copy of my logging object, which I will use in different places inside the class. In another case, I want to keep a simple type, the int value is actually used only internally (there should not be a property).

It seems that if I do not specify these variables as static, I cannot use them in Main () and beyond.

My understanding of static objects is that their values ​​are common to all instances of the object. In normal work, I would expect this to be only one instance of my application, so this problem is not a problem, but it emphasized the lack of understanding of my part of what is quite fundamental.

In the case of my logging object, I could see a case where it is static - sharing a log across multiple instances can be useful. However, this may not be so ... In the case of my int, I would never want this to be common to all instances.

So...

  • Do I misunderstand the theory of this?
  • Is there any other way to declare and use class level variables?
  • Should I avoid using them? I could just pass values ​​as parameters from function to function, although little is needed to work without visible improvements.

EDIT: OK, the message is clear - my understanding of statics was mostly correct, but the problem was one of structure and approach. Thank you for your responses.

+5
source share
3 answers

Just encapsulate your application in another class that you create and execute using the method Main:

class MyApp {
  private MyLog lol = new MyLog(); 
  private int myInt = 0;

  public void Execute() {
    // ...
  }
}

class Program {
  public static void Main() {
    new MyApp().Execute();
  }
}

You can still make the log field static if you want.

+9
source

You must create a class outside your main function, and then instantiate this class from Main.

E.G.

class MyConsoleApp
{
    public static void Main()
    {
        MyClass mc = new MyClass();
    }
}

Class MyClass
{
   private MyLog lol as new MyLog();
   private int myInt = 0;
}
+3
source

: , Main() , , . MyConsoleApp.

, ...

+2
source

All Articles