Global variables

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Paul Cheetham

    Global variables


    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.


    --
    Paul Cheetham

  • Andrew Ducker

    #2
    Re: Global variables

    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.

    Comment

    • Bruce Wood

      #3
      Re: Global variables

      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:



      Comment

      Working...