Creates a singleton class

    0

    2

    lucycodes42

    C# recipes

    The "instance" field is a protected field that keeps a reference to the current object. When a new object is created, it is stored in the "instance" field. The "syncRootObject" field is an object that is used to keep track of the current instance's synchronization root.

    Shortcut: singleton

    public sealed class MyClass
    {
      private static volatile IMyObject instance;
      private static Object syncRootObject = new Object();
    
      public static I${2} Instance
      {
        get
        {
          if (instance == null)
          {
            lock (syncRootObject)
            {
              if (instance == null)
              {
                instance = new MyObject();
              }
            }
          }
          return instance;
        }
      }
    }
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    Legal
    • Security
    • Privacy Policy
    • Code Privacy
    • Terms of Service
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.