// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; namespace E { public class MySingleton { private static MySingleton _instance = null; private static object mylock = new object(); private int _iv; private double _xv; private string _sv; private MySingleton() { _iv = 123; _xv = 123.456; _sv = "ABC"; } public static MySingleton Instance { get { lock(mylock) { if(_instance == null) { _instance = new MySingleton(); } } return _instance; } } public int IV { get { return _iv; } } public double XV { get { return _xv; } } public string SV { get { return _sv; } } } // bizarre attempt to stay fluent public static class MyFluentSingletonHelper { public static Tuple, MyFluentSingleton> GetInt(this Tuple, MyFluentSingleton> hlp) { hlp.Item1.Add("IV", hlp.Item2.IV); return hlp; } public static Tuple, MyFluentSingleton> GetDouble(this Tuple, MyFluentSingleton> hlp) { hlp.Item1.Add("XV", hlp.Item2.XV); return hlp; } public static Tuple, MyFluentSingleton> GetString(this Tuple, MyFluentSingleton> hlp) { hlp.Item1.Add("SV", hlp.Item2.SV); return hlp; } } public class MyFluentSingleton { private static MyFluentSingleton _instance = null; private static object mylock = new object(); private int _iv; private double _xv; private string _sv; private MyFluentSingleton() { _iv = 123; _xv = 123.456; _sv = "ABC"; } public static MyFluentSingleton Instance { get { lock(mylock) { if(_instance == null) { _instance = new MyFluentSingleton(); } } return _instance; } } public int IV { get { return _iv; } } public double XV { get { return _xv; } } public string SV { get { return _sv; } } public Tuple,MyFluentSingleton> Fluent() { return new Tuple,MyFluentSingleton>( new Dictionary(), this); } } public class Program { public static void Main(string[] args) { // refer every time Console.WriteLine("{0} {1} {2}", MySingleton.Instance.IV, MySingleton.Instance.XV, MySingleton.Instance.SV); // save ref MySingleton ms = MySingleton.Instance; Console.WriteLine("{0} {1} {2}", ms.IV, ms.XV, ms.SV); // fluent Dictionary dic = MyFluentSingleton.Instance.Fluent().GetInt().GetDouble().GetString().Item1; Console.WriteLine("{0} {1} {2}", dic["IV"], dic["XV"], dic["SV"]); } } }