What is singleton class in C#?
In C#, a singleton class is a class that can only have one instance, which is shared throughout the application. The singleton pattern is a design pattern that ensures that a class has only one instance, and provides a global point of access to that instance.
Here's an example of a singleton class:
public class Singleton
{
private static Singleton _instance;
private Singleton() { }
public static Singleton Instance
{
get
{
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
public void DoSomething()
{
// do something
}
}
In this example, the "Singleton" class has a private constructor, which means that it cannot be instantiated directly from outside the class. The class also has a static property called "Instance", which returns the single instance of the class. The property first checks if an instance of the class has already been created; if not, it creates a new instance and returns it.
You can access the single instance of the class using the "Instance" property, like this:
Singleton singleton = Singleton.Instance;
singleton.DoSomething();
In this example, the "Instance" property of the "Singleton" class is used to retrieve the single instance of the class. The "DoSomething" method of the class is then called on the instance.
Singleton classes are useful in scenarios where you want to ensure that there is only one instance of a class throughout the application. They can be particularly useful in managing shared resources, such as database connections, file handles, or network connections, where multiple instances of a class could cause conflicts or performance issues.
No comments:
Post a Comment
If you have any query kindly let me know.