Singleton Pattern C#

Singleton Pattern C# tutorial

Singleton Pattern is one the most popular patterns in programming. Singleton is a class which only allows a single instance of itself to be created. It can be very useful, for example when Class contains List of object we don’t want to create new list each time we call the class, and we also want to keep the list private to restrict access and avoid possible corruption. Singleton usually gives simple access to that instance. There are several ways of implementing the pattern, in multi-threading application we must consider case where constructor is called from two thread at the same time, to fix this problem we need to implement thread safety version. Let start with simplest, not thread safe, implementation.

public class Singleton
{
  private static Singleton instance;

  private Singleton() { }

  public static Singleton Instance
  {
    get
    {
       if (instance == null)
       {
          instance = new Singleton();
       }
       return instance;
    }
  }
 }

This Singleton class contains private static Singleton Class instance. Those keywords are very important, Private makes the instance accessible only from current class( Instance getter)  what prevents other classes from accessing it in not safe way. Static makes it shared across all instances. You can find more about statics, here.

Constructor of this class( Singleton() ) is private, and its called from Instance getter, if its not created yet.

Instance property is read only and it returns the instance of the class, always the same instance for all calls. If you don’t know how get{} works, check my post about it  here.

Here is thread safety version of this Pattern, It prevents from creating two instances when getter is called from multiple threads.

First we need to add object that will be responsible for handling multiple thread access.


private static readonly object padlock = new object();

New we need to add one condition to Instance parameter that will lock the firs thread that is accessing it.

public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }

 

All these implementations share four common characteristics, however:

  • A single constructor, which is private and parameterless.
  • A static variable which holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating one if necessary.

 

In next post You will see real word examples of using this patter. One day I’ll demonstrate how to use it In Unity to create MusicManager, that is playing music between game scenes. Singleton have many uses and It’s one of the simplest patterns to learn. In next articles I’ll try to describe all most popular design patterns. Stay Awesome!

C# Statics

Static keyword is used to access the method or variable without creating instance of the class. Static effectively  means “associated with a type instead of any one instance of the type”. This keyword can be used in multiple structures. IN this article i’ll focus on static keyword used with methods, classes and variables. First lets take look at variables.

Static Variables

Static variables allows to access the values from other class,if its public, without creating the instance of the object.

In My example use MyClass to store two static fields with initial values. I can acess those variabels from Program Class. I dont need instance of the class to call the variables.

class Program
{
  static void Main(string[] args)
  {
      Console.WriteLine(MyClass.i.ToString()+" "+MyClass.name);
  }
}

class MyClass
{
  public static int i=0;
  public static string name="John";
}

Static  Methods

To call static method we don’t need  an instance of the class—this makes them slightly faster. Static methods can be both public or private.  A static method cannot access non-static class level members. It has no “this” pointer. We can not refer to non-static fields from static method.

This is modified version of previous example. This time I have just one static method in MyClass. I’m calling this method from Program class without creating the instance of an object.

 

class Program
{
  static void Main(string[] args)
  {
      MyClass.Print();
  }

}
class MyClass
{
  public static void Print()
  {
     Console.WriteLine("This is Static method");
  }
}

 

Static Classes

A static class is never instantiated. The static keyword on a class enforces that a type not be created with a constructor. Class with static keyword can not have any instances.This eliminates misuse of the class.

A static class is a class which can only contain static members. Like variables and methods from previous examples.

static class MyClass
// Line below can not be executed. 

// MyClass a = new MyClass();

Now you know the basic implementation of static keyword it can be useful when working with large and complex projects whits a lot of connections. Statics can improve the performance and make variables/methods easier to access. In my Unity Tutorials I’ll demonstrate the use of statics in real word examples. Stay Awesome!