Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Clarification on this answer: This doesn't exactly address the <em>question</em> asked, but the implementation that was linked to above is horribly coded. Perhaps the implementation below would be thread safe.</p> <p>I'm not 100% sure that this is thread safe because I did not test it (and I can't come up with any real world use of this "pattern" because I think it is confusing), but it is a more correct Singleton-like implementation of what you linked to above and might work to accomplish what you wanted. Good luck.</p> <p>Sorry about the <code>Console.WriteLine()</code> calls, I used Snippet Compiler to make this.</p> <pre><code>/// &lt;summary&gt; /// Doubleton /// &lt;/summary&gt; public sealed class Doubleton { const int MaxInstances = 2; static volatile Hashtable instances = new Hashtable(); static volatile int PreviousInstanceNumber = MaxInstances; #region Constructor Doubleton() { } #endregion #region Properties /// &lt;summary&gt; /// Get 1 of 2 instances of a Doubleton /// &lt;/summary&gt; public static Doubleton Instance { get { lock (instances.SyncRoot) { int instanceNumber = PreviousInstanceNumber == MaxInstances ? 1 : ++PreviousInstanceNumber; // if it doesn't exist, create it if (instances[instanceNumber] == null) { instances[instanceNumber] = new Doubleton(); } PreviousInstanceNumber = instanceNumber; return (Doubleton)instances[instanceNumber]; } } } #endregion /// &lt;summary&gt; /// Get the index of the Doubleton /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; public int GetInstanceIndex() { lock (instances.SyncRoot) { for (int i = 1; i &lt;= MaxInstances; i++) { if (instances[i] != null &amp;&amp; instances[i].Equals(this)) { return i; } } } return -1; } } </code></pre> <p>You could then use the following code:</p> <pre><code>var instance1 = Doubleton.Instance; var instance2 = Doubleton.Instance; var instance1Again = Doubleton.Instance; var instance2Again = Doubleton.Instance; Console.WriteLine("The following 2 lines should be true:"); Console.WriteLine(instance1.Equals(instance1Again)); Console.WriteLine(instance2.Equals(instance2Again)); Console.WriteLine("---"); Console.WriteLine("The next 50 lines should alternate instances:"); for (int i = 0; i &lt; 50; i++) { var instance = Doubleton.Instance; Console.WriteLine("I have instance # " + instance.GetInstanceIndex()); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload