I thought the point of a singleton was I could only initialize one instance at a time? If this is correct, then I must have a fault in my C# console application code (see below).
Would some one please be kind enough to inform me if my understanding of a singleton is correct or if there is an error in my code.
using System;
using System.Collections.Generic;
using System.Text;
namespace TestSingleton
{
class Program
{
static void Main(string[] args)
{
Singleton t = Singleton.Instance;
t.MyProperty = "Hi";
Singleton t2 = Singleton.Instance;
t2.MyProperty = "Hello";
if (t.MyProperty != "")
Console.WriteLine("No");
if (t2.MyProperty != "")
Console.WriteLine("No 2");
Console.ReadKey();
}
}
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
public string MyProperty { get; set; }
private Singleton()
{}
static Singleton()
{ }
public static Singleton Instance { get { return instance; } }
}
}
Infact you have only one instance here. You get 2 pointers
But they both are pointing to the same memory location.