---
title: "Thread-safe Singleton Pattern Example in C#"
author: "chenying998179"
date: "2012-04-23T00:50:53Z"
tags: []
categories: ["编程语言"]
slug: "thread-safe-singleton-pattern-example-in-c"
draft: false
lastmod: "2012-04-22T00:13:27Z"
id: 1493667
url: "https://chenying99.iteye.com/blog/1493667"
---

The Singleton pattern is used when you need one, and only one instance of your class. Sometimes you see this pattern used in cases where the construction of a class is expensive (like a file stream). It can be lazy loaded (at runtime instead of compiletime) and must be thread-safe. The class gets a public method or property named Instance, responsible for creating the Singleton. The constructor of the Singleton class is private, so no one can construct a new instance from the class by applying ‘new’.

[![](http://www.remondo.net/wp-content/uploads/2012/01/SingletonPatternClassDiagram.png "SingletonPatternClassDiagram")](http://www.remondo.net/wp-content/uploads/2012/01/SingletonPatternClassDiagram.png)

```
using System;

namespace Singleton
{
    class Program
    {
        static void Main(string[] args)
        {
            // Lazy loaded object
            // Singleton gets created on first call
            Singleton.Instance.SomeProperty = 0;
            Singleton.Instance.SomeMethod();
        }
    }

    public class Singleton
    {
        // Private constructor to prevent 'new'
        private Singleton()
        {
        }

        // The instance read only property
        public static Singleton Instance
        {
            get
            {
                return Nested.instance;
            }
        }

        // Nested class with the actual Singleton object
        private class Nested
        {
            internal static readonly Singleton instance =
                new Singleton();

            static Nested()
            {
            }
        }

        // Additional methods and propeties
        public int SomeProperty { get; set; }
        public void SomeMethod() { }
    }
}
```