Ajay Ajay - 2 months ago 14
C# Question

How can we create a clone object of Singleton Instance?

I am having a singleton class in my code.

In my main function, I created an object of that class.

Then, I tried to create the clone for that object.

And, it gave me "StackOverflowException".

My code looks like:

namespace SingletonApplication
{
class A : ICloneable
{
private static readonly A A1 = new A();

public A A2 { get { return A1; } }
public object Clone()
{
var obj = ((ICloneable)A1).Clone();
return obj;
}
}


class Program
{
static void Main(string[] args)
{
A obj1 = new A();
A obj2 = (A)(obj1.Clone());

Console.WriteLine(object.ReferenceEquals(obj1.A2, obj2.A2));

Console.ReadKey();
}

}
}


Error:
enter image description here

Answer

The requirments are contradictory ones:

  • Singleton can have at most one instance by its own definition
  • Clone() methos is supposed to produce a clone, a new (== second) instance

Probably a better solution is to return a fake clone (i.e. itself)

   // sealed: do not inherit from me (Singleton) and create a second copies
   sealed class A : ICloneable
   {
       private static readonly A A1 = new A();

       //private constructor: do not create instances (I'm a Sinleton)
       private A();

       public A A2 { get { return A1; } }

       // We can't create a new clone but can return an existing instance
       public object Clone()
       {
           // Cloned Siongleton? Let it be itself
           return this;
       }
   }