Alois Kraus


  Home  |   Contact  |   Syndication    |   Login
  133 Posts | 8 Stories | 368 Comments | 162 Trackbacks




Singletons are the easiest programming pattern to learn which seems to be the reason why it is often used in places where it is inappropriate. They are very straightforward to implement and understand. Just create a static field and return the static instance in a public get property. A Logger Singleton is a classic example of this pattern:

        public class Logger

        static LogWriter writer = new LogWriter();

        public static LogWriter Writer


            get    { return writer; }



If you wrote such code before and thought that this is perfectly working in all cases I must disappoint you. There are subtle things going on when static fields are initialized by the CLR. This implementation is thread safe because static fields are initialized only once by the CLR before any method can be called or a static field can be accessed from the outside. More details can be found inside the ECMA-334 C# Language Specification and ECMA-335 Common Language Infrastructure (CLI). Now comes the tricky part. When do you think will be LogWriter instance be instantiated? To answer this question let's have a look at two nearly identical Singletons.

Show more ...

posted on Sunday, September 10, 2006 8:36 PM