Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a singleton in C#?

Tags:

How do I implement the singleton pattern in C#? I want to put my constants and some basic functions in it as I use those everywhere in my project. I want to have them 'Global' and not need to manually bind them every object I create.

like image 906
Andre Avatar asked Oct 29 '08 13:10

Andre


People also ask

How do you implement a singleton?

The most popular approach is to implement a Singleton by creating a regular class and making sure it has: A private constructor. A static field containing its only instance. A static factory method for obtaining the instance.

What is a singleton object in C?

Singleton in C++ Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code. Singleton has almost the same pros and cons as global variables. Although they're super-handy, they break the modularity of your code.

What is the best way to implement a singleton class?

Eager initialization: In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a Singleton class. By making the constructor as private you are not allowing other class to create a new instance of the class you want to create the Singleton.

How do you declare a singleton class in C#?

Singleton Class allow for single allocations and instances of data. It has normal methods and you can call it using an instance. To prevent multiple instances of the class, the private constructor is used.


1 Answers

If you are just storing some global values and have some methods that don't need state, you don't need singleton. Just make the class and its properties/methods static.

public static class GlobalSomething {    public static int NumberOfSomething { get; set; }     public static string MangleString( string someValue )    {    } } 

Singleton is most useful when you have a normal class with state, but you only want one of them. The links that others have provided should be useful in exploring the Singleton pattern.

like image 93
tvanfosson Avatar answered Oct 15 '22 18:10

tvanfosson