{"id":1501,"date":"2023-04-11T08:20:11","date_gmt":"2023-04-11T01:20:11","guid":{"rendered":"https:\/\/csharptutorial.net\/?page_id=1501"},"modified":"2024-12-14T22:59:09","modified_gmt":"2024-12-14T15:59:09","slug":"csharp-singleton","status":"publish","type":"page","link":"https:\/\/www.csharptutorial.net\/csharp-design-patterns\/csharp-singleton\/","title":{"rendered":"C# Singleton"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you will learn how to use the C# Singleton pattern to ensure a class has only one instance.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to the C# Singleton pattern<\/h2>\n\n\n\n<p>Sometimes, you need to create one and only one instance of a <a target=\"_blank\" href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-class\/\" rel=\"noreferrer noopener\">class<\/a>. The reason is that creating multiple instances of such a class may lead to problems like incorrect data or resource contention.<\/p>\n\n\n\n<p>For example, when you work with a logging framework or database connection.<\/p>\n\n\n\n<p>The Singleton pattern solves the problem of creating a single instance of a class that should be globally accessible throughout the application.<\/p>\n\n\n\n<p>The Singleton pattern is a creational design pattern that ensures a class has only one instance and provides a global access point to that instance.<\/p>\n\n\n\n<p>The UML diagram below illustrates the Singleton design pattern.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" src=\"https:\/\/csharptutorial.net\/wp-content\/uploads\/2023\/04\/CSharp-Singleton-Pattern.svg\" alt=\"\" class=\"wp-image-1526\"\/><\/figure>\n\n\n\n<p>The Singleton pattern consists of a single class responsible for creating and maintaining a single instance.<\/p>\n\n\n\n<p>The participants in the Singleton pattern are:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>Singleton<\/code>: is a class for creating and maintaining a single instance.<\/li>\n\n\n\n<li><code>Client<\/code>: is the class that uses the Singleton instance.<\/li>\n<\/ul>\n\n\n\n<p>The <code>Singleton<\/code> class is responsible for creating a single instance. The <code>Client<\/code> class gets the <code>Singleton<\/code> instance by calling the <code>Instance<\/code> accessor or <code>GetInstance()<\/code> method.<\/p>\n\n\n\n<p>The <code>Singleton<\/code> class has a constructor marked as <a href=\"https:\/\/csharptutorial.net\/csharp-tutorial\/csharp-public-private\/\">private<\/a> to prevent other classes from creating instances of the <code>Singleton<\/code> class.<\/p>\n\n\n\n<p>The <code>Singleton<\/code> class also has an accessor that provides access to the instance.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Singleton Pattern Pros &amp; Cons<\/h2>\n\n\n\n<p>The Singleton pattern offers several benefits, including:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Ensure only one instance of the class.<\/li>\n\n\n\n<li>Provide a global point of access to the instance.<\/li>\n\n\n\n<li>Provide a way to control access to the instance.<\/li>\n<\/ul>\n\n\n\n<p>In addition to the benefits mentioned above, the Singleton pattern has several drawbacks:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Difficult to test. The Singleton pattern can make testing more difficult. The Singleton pattern creates a global point of access to the instance, which leads to unexpected dependencies in test cases.<\/li>\n\n\n\n<li>Lead to tight coupling between classes. Classes that depend on the Singleton instance are aware of its existence and how to access it, which may lead to a strong coupling between the classes. As a result, it&#8217;s challenging to change the Singleton class or the classes that depend on the Singleton class without affecting other parts of the system.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Singleton implementation in C#<\/h2>\n\n\n\n<p>The following illustrates how to use implement the Singleton pattern in C#:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">sealed<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Singleton<\/span>\n{\n    <span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">static<\/span> Singleton? _instance;\n\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">static<\/span> Singleton Instance\n    {\n        <span class=\"hljs-keyword\">get<\/span>\n        {\n            _instance ??= <span class=\"hljs-keyword\">new<\/span> Singleton();\n            <span class=\"hljs-keyword\">return<\/span> _instance;\n        }\n    }\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-title\">Singleton<\/span>(<span class=\"hljs-params\"><\/span>)<\/span>\n    {\n    }\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>How it works.<\/p>\n\n\n\n<p>First, define the <code>Singleton<\/code> class with the <code>sealed<\/code> keyword so that other classes will not be able to inherit from this class.<\/p>\n\n\n\n<p>Second, declare a <code>static private<\/code> field with the type <code>Singleton<\/code> called <code>_instance<\/code>.<\/p>\n\n\n\n<p>Third, define the accessor that creates an instance of the <code>Singleton<\/code> class if it is <code>null<\/code>; otherwise, return the instance. This accessor is the only way to access the <code>Singleton<\/code> instance. <\/p>\n\n\n\n<p>Finally, mark the constructor of the <code>Singleton<\/code> class as <code>private<\/code> to prevent other classes from creating a new instance of the <code>Singleton<\/code> class.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">C# Singleton example<\/h2>\n\n\n\n<p>The following program demonstrates how to apply the Singleton pattern to define a <code>Logger<\/code> class that has one and only one instance throughout the application:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\"><span class=\"hljs-keyword\">namespace<\/span> <span class=\"hljs-title\">DP<\/span>;\n\n<span class=\"hljs-keyword\">sealed<\/span> <span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Logger<\/span>\n{\n    <span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-keyword\">static<\/span> Logger? _instance;\n    <span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">static<\/span> Logger Instance\n    {\n        <span class=\"hljs-keyword\">get<\/span>\n        {\n            _instance ??= <span class=\"hljs-keyword\">new<\/span> Logger();\n            <span class=\"hljs-keyword\">return<\/span> _instance;\n        }\n    }\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">private<\/span> <span class=\"hljs-title\">Logger<\/span>(<span class=\"hljs-params\"><\/span>)<\/span>\n    {\n    }\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">Log<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">string<\/span> message<\/span>)<\/span>\n    {\n        Console.WriteLine(message);\n    }\n}\n\n<span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Program<\/span>\n{\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">public<\/span> <span class=\"hljs-keyword\">static<\/span> <span class=\"hljs-keyword\">void<\/span> <span class=\"hljs-title\">Main<\/span>(<span class=\"hljs-params\"><span class=\"hljs-keyword\">string<\/span>&#91;] args<\/span>)<\/span>\n    {\n        <span class=\"hljs-keyword\">var<\/span> logger = Logger.Instance;\n        logger.Log(<span class=\"hljs-string\">\"C# Singleton\"<\/span>);\n    }\n}<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"C#\" data-shcb-language-slug=\"cs\"><span><code class=\"hljs language-cs\">C<span class=\"hljs-meta\"># Singleton<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">C#<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">cs<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\">Singleton applications<\/h2>\n\n\n\n<p>Here are some practical applications of the Singleton pattern:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Managing resources such as thread pools, database connections, and caches.<\/li>\n\n\n\n<li>Logging and auditing frameworks that need to maintain a single log or audit trail throughout the system.<\/li>\n\n\n\n<li>Configuration management, where you need one and only one instance of the configuration manager that is accessible from any part of the system.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Summary<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use the Singleton pattern to ensure that a class has one and only one instance through the application.<\/li>\n\n\n\n<li>The Singleton can make the application difficult to test and may lead to tight coupling between classes.<\/li>\n<\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"1501\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-design-patterns\/csharp-singleton\/\"\n\t\t\t\tdata-post-title=\"C# Singleton\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"1501\"\n\t\t\t\tdata-post-url=\"https:\/\/www.csharptutorial.net\/csharp-design-patterns\/csharp-singleton\/\"\n\t\t\t\tdata-post-title=\"C# Singleton\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\n\t\t\t<button class=\"btn btn-primary wth-btn-submit\">Send<\/button>\n\t\t\t<button class=\"btn wth-btn-cancel\">Cancel<\/button>\n\t\t\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you will learn about the C# Singleton pattern to ensure a class has a single instance that can be accessed globally.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":1441,"menu_order":5,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-1501","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/1501","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/comments?post=1501"}],"version-history":[{"count":5,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/1501\/revisions"}],"predecessor-version":[{"id":2714,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/1501\/revisions\/2714"}],"up":[{"embeddable":true,"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/pages\/1441"}],"wp:attachment":[{"href":"https:\/\/www.csharptutorial.net\/wp-json\/wp\/v2\/media?parent=1501"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}