How to use singleton design pattern for a single allocations of an object in C#

2 Answers

0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        public sealed class Test
        {
            static readonly Test _instance = new Test();
            public static Test Instance
            {
                get
                {
                    return _instance;
                }
            }
            Test()
            {
                Console.WriteLine("Test()");
            }
        }

        static void Main(string[] args)
        {
            Test o1 = Test.Instance;

            Test o2 = Test.Instance;

            Test o3 = Test.Instance;
        }
    }
}


/*
run:
  
Test()
 
*/

 



answered Jan 9, 2017 by avibootz
0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        public class Test
        {
            public static readonly Test _instance = new Test();

            Test()
            {
                Console.WriteLine("Test()");
            }
            public void Method()
            {
                Console.WriteLine("Method()");
            }
        }

        static void Main(string[] args)
        {
            Test._instance.Method();

            Console.WriteLine();

            Test._instance.Method();

            Console.WriteLine();

            Test._instance.Method();
        }
    }
}


/*
run:
  
Test()
Method()

Method()

Method()
 
*/

 



answered Jan 9, 2017 by avibootz
...