AboutSQL Server, Analytics, .Net, Machine Learning, R, Python Archives
About Me
Mitch Wheat has been working as a professional programmer since 1984, graduating with a honours degree in Mathematics from Warwick University, UK in 1986. He moved to Perth in 1995, having worked in software houses in London and Rotterdam. He has worked in the areas of mining, electronics, research, defence, financial, GIS, telecommunications, engineering, and information management. Mitch has worked mainly with Microsoft technologies (since Windows version 3.0) but has also used UNIX. He holds the following Microsoft certifications: MCPD (Web and Windows) using C# and SQL Server MCITP (Admin and Developer). His preferred development environment is C#, .Net Framework and SQL Server. Mitch has worked as an independent consultant for the last 10 years, and is currently involved with helping teams improve their Software Development Life Cycle. His areas of special interest lie in performance tuning |
Sunday, January 07, 2007.Net C# Singleton Pattern - Best Practice
What is the best practice way to implement the Singleton design pattern in C#? You might be surprised at the number of flawed examples there are out there; many of the articles I looked at were incorrect (some subtlely, some not so) and several were on high traffic, popular sites!
This excellent article by Jon Skeet not only discusses several ways not to do it, but also the correct way: public sealed class Singleton { // Prevent compiler adding a default public parameterless constructor private Singleton() {} public static readonly Singleton Instance = new Singleton(); // Explicit static constructor instructs compiler // NOT to mark type as ‘beforefieldinit’ // Remove this if you do not need to guarantee lazy instantiation static Singleton() {} } The static constructor is only required if you want to guarantee lazy instantiation (which Jon explains here.) See also this MSDN article from Feb 2002. |
ContactMSN, Email: mitch døt wheat at gmail.com LinksFavorites
Blogs |