A static class and a singleton are two different design patterns in C# that are used for different purposes.
A static class is a class that can only contain static members (methods, properties, fields). It cannot be instantiated, and all its members are accessible through the class name itself. A static class is typically used to group related utility methods or constants that do not require any state or instance-specific behavior.
Here's an example of a static class:
public static class Calculator
{
public static int Add(int x, int y)
{
return x + y;
}
public static int Multiply(int x, int y)
{
return x * y;
}
}
A singleton, on the other hand, is a class that can have only one instance throughout the lifetime of the application. It typically has a private constructor to prevent direct instantiation and provides a static method or property to access the singleton instance. A singleton is often used to represent a global state or to provide a centralized point of access to a resource or service.
Here's an example of a singleton:
public class Logger
{
private static Logger instance;
private static readonly object lockObject = new object();
private Logger()
{
// Private constructor to prevent direct instantiation
}
public static Logger Instance
{
get
{
// Double-checked locking to ensure thread-safety
if (instance == null)
{
lock (lockObject)
{
if (instance == null)
{
instance = new Logger();
}
}
}
return instance;
}
}
public void Log(string message)
{
// Logging implementation
}
}
The main difference between a static class and a singleton is that a static class cannot be instantiated, whereas a singleton can have one instance. A static class is typically used to group related utility methods or constants, while a singleton is often used to represent a global state or to provide a centralized point of access to a resource or service.