C# Singleton, Static Class

One: 1

A singleton stores common data in only one place. A static class is also used to store single-instance data. We save state between usages. We store caches to improve performance. The object must be initialized only once and shared.

Singleton Class

Example

Note

First you can implement singletons by using language-specific features, such as the static keyword. Our ideal solution is called the singleton design pattern. As you know, a singleton is a single-instance object.

And:A singleton can simplify complex code. Singletons have a static property that you must access to get the object reference.

Singleton implementation: C#

/// <summary>
/// Sample singleton object.
/// </summary>
public sealed class SiteStructure
{
    /// <summary>
    /// This is an expensive resource.
    /// We need to only store it in one place.
    /// </summary>
    object[] _data = new object[10];

    /// <summary>
    /// Allocate ourselves.
    /// We have a private constructor, so no one else can.
    /// </summary>
    static readonly SiteStructure _instance = new SiteStructure();

    /// <summary>
    /// Access SiteStructure.Instance to get the singleton object.
    /// Then call methods on that instance.
    /// </summary>
    public static SiteStructure Instance
    {
	get { return _instance; }
    }

    /// <summary>
    /// This is a private constructor, meaning no outsiders have access.
    /// </summary>
    private SiteStructure()
    {
	// Initialize members here.
    }
}
This section provides information

In the example above, the member called _instance is a static instance of the SiteStructure class. This means it only can be created once by the runtime. Static members only exist in one place.

Readonly Fields

We use this static reference to an actual, regular object. The Instance static property allows easy access to the SiteStructure singleton. This is a public property and is also called a getter.

Property ExamplesPrivate keyword

A private constructor means that a class cannot be created anywhere but inside its own methods. So it must be accessed through the singleton reference. It uses the sealed keyword decoration to improve some optimization options.

Private ConstructorSealed Keyword

Static class

Static

You can make a static class with the static keyword. In the following example, look at how the static keyword is used on the class and constructor. Static classes may be simpler, but the singleton example has many important advantages.

Static Class

Differences:There are important differences between the singleton design pattern and the static keyword on classes.

And:Static classes and singletons both provide sharing of redundant objects in memory, but they differ in usage and implementation.

Static class example: C#

/// <summary>
/// Static class example. Note the static keyword usage.
/// </summary>
static public class SiteStatic
{
    /// <summary>
    /// The data must be a static member in this example.
    /// </summary>
    static object[] _data = new object[10];

    /// <summary>
    /// C# doesn't define when this constructor is run, but it will likely
    /// be run right before it is used.
    /// </summary>
    static SiteStatic()
    {
	// Initialize all of our static members.
    }
}
Note

Using static classes for global data. You can use static classes to store single-instance, global data. The class will usually be initialized lazily, at the last possible moment, making startup faster.

However:You lose control over the exact behavior and static constructors are slow.

Static Constructor

Singleton

Programming tip

Singletons preserve the conventional class approach, and don't require that you use the static keyword everywhere. They may be more demanding to implement at first, but will greatly simplify the architecture of your program.

And:Unlike static classes, we can use singletons as parameters to methods, or objects.

Parameter Passing, Ref and OutObject Type
Using singleton as parameter: C#

//
// We want to call a function with this structure as an object.
// Get a reference from the Instance property on the singleton.
//
SiteStructure site = SiteStructure.Instance;
OtherFunction(site); // Use singleton as parameter.

Interfaces

C# programming language

You can use singletons with interfaces just like any other class. In the C# language, an interface is a contract, and objects that have an interface must meet all of the requirements of that interface.

Reusing the singleton. Here we can use the singleton on any method that accepts the interface. We don't need to rewrite anything over and over again. These are object-oriented programming best practices.

Tip:You can find more detailed examples on the interface type in the C# language here.

Interface
Singletons used with interface: C#

/// <summary>
/// Stores signatures of various important methods related to the site.
/// </summary>
public interface ISiteInterface
{
};

/// <summary>
/// Skeleton of the singleton that inherits the interface.
/// </summary>
class SiteStructure : ISiteInterface
{
    // Implements all ISiteInterface methods.
    // [omitted]
}

/// <summary>
/// Here is an example class where we use a singleton with the interface.
/// </summary>
class TestClass
{
    /// <summary>
    /// Sample.
    /// </summary>
    public TestClass()
    {
	// Send singleton object to any function that can take its interface.
	SiteStructure site = SiteStructure.Instance;
	CustomMethod((ISiteInterface)site);
    }

    /// <summary>
    /// Receives a singleton that adheres to the ISiteInterface interface.
    /// </summary>
    private void CustomMethod(ISiteInterface interfaceObject)
    {
	// Use the singleton by its interface.
    }
}

Summary

Singletons allow you to reuse code and control object state much easier. This improves code-sharing, and can result in a far cleaner body of code. With less code, your programs will usually have fewer bugs and will be easier to maintain.


C#: Static