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?

有帮助吗?

解决方案

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).

其他提示

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?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top