How to create global object in a C# library

Stefanos Kargas picture Stefanos Kargas · Jan 13, 2013 · Viewed 31.3k times · Source

Possible Duplicate:
Best way to make data (that may change during run-time) accessible to the whole application?

I have a C# library.

  1. Can a library have global objects/variables?
  2. Can an initialization method for those objects be automatically executed from a library when running the main project or do I have to make it a static method and run it from the main project?

Answer

Hogan picture Hogan · Jan 13, 2013

In C# I always use a static classes to provide this functionality. Static classes are covered in detail here, but briefly they contain only static members and are not instantiated -- essentially they are global functions and variables accessed via their class name (and namespace.)

Here is a simple example:

public static class Globals
{
    public static string Name { get; set; }
    public static int aNumber {get; set; }
    public static List<string> onlineMembers = new List<string>();

     static Globals()
     {
        Name = "starting name";
        aNumber = 5;
     }
}

Note, I'm also using a static initializer which is guaranteed to run at some point before any members or functions are used / called.

Elsewhere in your program you can simply say:

Console.WriteLine(Globals.Name);
Globals.onlineMemeber.Add("Hogan");

Static objects are only "created" once. Thus everywhere your application uses the object will be from the same location. They are by definition global. To use this object in multiple places simply reference the object name and the element you want to access.


You can add static members to any class and they will be globally available, but I think having one place for globals is a better design.