Differences between a static constructor and permutation of a static instance in a global class

What is the difference between a static constructor like:

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

And a static instance is defined in the global class as follows:

 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 the difference between each type? And what is better to use?

+4
source share
2 answers

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

In the second case, the database is initialized each time a GlobalClass instance is GlobalClass . No instances - no initializations. Two instances - two initializations (only the last will be available through the dataBase field).

+3
source

Although initially similar functions do not match,

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

The biggest advantage is that Globals can be assigned, it can be reassigned. One use is where you have several subtypes of GlobalClass , you can assign an instance of the corresponding subtype to a given context.

You can read more about Singleton and static here: The difference between a static class and a singleton template?

+1
source

Source: https://habr.com/ru/post/1489723/


All Articles