views:

102

answers:

3

This is definitely a bit of a noob question, but my searches so afar haven't cleared the issue up for me.

A want a particular console app to store several class-level variables. In one case, I want to store a copy of my logging object, which I'll use in various places within the class. In another case, I want to store a simple type, a int value actually, which is only going to be used internally (doesn't need to be a property).

It appears that unless I specify these variables as static, I can't use them in Main() and beyond.

My understanding of static objects is that their values are shared across all instances of an object. Under normal operation, I'd expect their to be only one instance of my app, so this issue isn't a problem - but it has highlighted a lack of understanding on my part of something that is fairly fundamental.

In the case, of my logging object, I could see a case for making it static - sharing a log across multiple instances might be a benefit. However, it might not be the case... In the case of my int, I'd certainly never want this to be shared across instances.

So...

  • Am I misunderstanding the theory behind this?
  • Is there a different way I should be declaring and using my class-level variables?
  • Should I be avoiding using them? I could simply pass values as parameters from function to function, though it seems little a lot for work for no apparent gain.

EDIT: OK, the message is clear - my understanding of statics was largely correct, but the problem was one of structure and approach. Thanks for your replies.

+3  A: 

You should be creating a class outside of your Main function, and then creating an instance of that class from within Main.

EG

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

Class MyClass
{
   private MyLog lol as new MyLog();
   private int myInt = 0;
}
DJ Quimby
+7  A: 

Just encapsulate your application in another class, which you create and execute on the Main method:

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.

Jordão
+1, and ["Global Variables are Bad"](http://c2.com/cgi/wiki?GlobalVariablesAreBad) does a good job of explaining why it's worth going to the trouble.
Jeff Sternal
+2  A: 

The issue here is more or less purely syntactical: Because a static method can only access static fields, and the Main() method has to be static, this requires the used variables to be static. You never create an instance of the MyConsoleApp class.

Not really much theory here, only pragmatic requirements...

Thomas

Thomas Weller