Question

What is differences between static constructor as the following:

class GlobalClass
{

    public static DataBase dataBase;

    static GlobalClass()
    {
        dataBase= new DataBase(@"Data Source=..;...; User ID=... ;Password=...;");
        dataBase.CreateConnection();
    }
}

And defined static instance in global class as the following:

class GlobalClass
{

    public static GlobalClass Globals = new GlobalClass();

    public DataBase dataBase;

    public  GlobalClass()
    {
        dataBase= new DataBase(@"Data Source=..;...; User ID=... ;Password=...;");
        dataBase.CreateConnection();
    }
}

What is differences between each type? And which is better to use?

Was it helpful?

Solution

In first case database initialized only once, when GlobalClass accessed first time.

In second case database initialized each time when you create GlobalClass instance. No instances - no initializations. Two instances - two initializations (only last one will be available via dataBase field).

OTHER TIPS

While initially similar in function they are not the same.

The second version is an implementation of the Singleton pattern, is the more flexible of the two.

The biggest advantage is since Globals is assignable, it can be reassigned. One use is where you have multiple subtypes of the GlobalClass, you can assign an instance of the appropriate subtype for the given context.

You can read more about Singleton versus static here: Difference between static class and singleton pattern?

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