Question

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?
Was it helpful?

Solution

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.

OTHER TIPS

You can use public static properties on a class as global objects/variables.

You can initialize static properties in a static constructor for the class, which will be called directly before the first time the properties are accessed.

Can a library have global objects/variables?

Yes c# can have static classes, static members. But No variables can exist outside class.

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?

Either you can initialize inline, or do initialization in static constructors. They are called before first access to any static members or instance members. If static members are not accessed and instances are not created, there is a chance that initialization will not take place.

Interesting article related to static initializers

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top