Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a class which can only have a single instance in C#

I wonder if there is a mechanism or pattern to allow only one instance of a class in C#. I have heard of the Singleton class, but i don't know how to use it well.

like image 349
Tom Sarduy Avatar asked Jun 12 '11 05:06

Tom Sarduy


1 Answers

Using singleton, that is a class which only allows a single instance of itself to be created.

public sealed class Singleton
{
     public static readonly Singleton instance = new Singleton();
     private Singleton() {}
}

The operation of this pattern is simple and could be reduced to the following:

Hide the constructor of the Singleton class, so that clients may not be instantiated. To declare the Singleton class private member variable containing the reference to the unique instance that we handle. Provide in class Singleton a function or property that provides access to the one maintained by the Singleton instance.

like image 172
Ruben Capote Avatar answered Sep 30 '22 02:09

Ruben Capote