Global variables

  • Thread starter Thread starter Paul Cheetham
  • Start date Start date
P

Paul Cheetham

OK, I know you can't have globals in C#, and I know that they are abused
in other languages, but sometimes they are the best answer:

I have a Settings Class. I would like to create a single instance of
this settings class so that my other classes can use it to read / write
their settings. This saves time and memory etc over each class creating
its own instance.
In C++ or VB I would have a global instance of the settings class, which
all other classes would be able to see and use.


Can anyone tell me the best way to go about solving my problem in C#?


Thankyou.
 
A 'static' class. Static methods can be called without creating an
instance of your class - for instance, DateTime.Parse is a static
method on the DateTime class - you can call it without having to create
a DateTime class. You can use these as global variables, should you
wish to. Just don't overuse them.
 
Another method is a Singleton. The Singleton pattern creates exactly
one instance of a class. If you've programmed C++, you'll know that
Singletons are handy if you should want to be able to have various
implementations of your Settings: for example, a TestSettings class for
unit testing, in addition to the production class.

Jon Skeet has a good writeup on Singleton:

http://www.yoda.arachsys.com/csharp/singleton.html
 
Back
Top