If you don’t know this pattern already, this is a must have in order to advance your career as a C# developer. The Singleton is very simple and very powerful, it works by ensuring that a class has only one instance while providing a global point of access to that instance. This pattern is particularly useful in scenarios where a single point of control is necessary, such as managing configurations or database connections.

The pattern restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. You can implement it by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it returns a reference to that object.

C# Example

Implementing the Singleton pattern in C# is straightforward. Here’s a basic approach:

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

    private Singleton() { }

    public static Singleton Instance
    {
        get { return _instance; }
    }
}

Now the above example is useless in real life so let’s use a more practical real life example that I have seen used in my career:

public class JsonSerializerSettings
{
    private static readonly JsonSerializerOptions _options = new JsonSerializerOptions
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        WriteIndented = true,
        PropertyNameCaseInsensitive = true
    };
    
    private JsonSerializerSettings()
    {
    }

    public static JsonSerializerOptions Options
    {
        get { return _options; }
    }
}

With the JsonSerializerSettings Singleton implemented, you can access your application-wide JSON settings from anywhere in your application. Here’s how you might use it to serialize and deserialize data:

var myObject = new Person { Name = "John Doe", Age = 30 };

string jsonString = JsonSerializer.Serialize(myObject, JsonSerializerSettings.Options);

var deserializedObject = JsonSerializer.Deserialize<Person>(jsonString, JsonSerializerSettings.Options);

Conclusion

The Singleton pattern is a must know pattern in my opinion. In this post we managed to cover the basics of it. Learning how to leverage it can help with performance and maintain consistency in our applications.

If you love learning new stuff and want to support me, consider buying a course like From Zero to Hero: Kubernetes for Developers or by using this link to buy a course from dometrain.com ❤

Leave a comment

Trending