Type intializer error on Singleton class

Posted on 2008-06-15
Medium Priority
Last Modified: 2013-12-17
Hi all

When I run the main windows application  and create the following singleiton class I get the following error.

public class HDPaint
        #region Singleton implementation

        private HDPaint() { }

        /// <summary>
        /// Thread-safe singleton implementation
        /// </summary>
        public static readonly HDPaint currInstance = new HDPaint(); // error line

{"The type initializer for 'hdps.classLib.HdpsOrder' threw an exception."}

Question by:AdibRahman77
LVL 12

Expert Comment

ID: 21789613
Run it in the IDE with break-on-exception enabled, and you'll find out what the problem is, won't you?
LVL 30

Accepted Solution

anarki_jimbel earned 1500 total points
ID: 21789775
Your implementation is wrong. You maty find classic implementation on msdn:

Syntactically your code is OK. However, instance of a singleton should be returned through a public property. And the property has to return same instance for every call. In your case the public field returns new instance for every call - not a singleton at all.
public class Singleton
   private static Singleton instance;
   private Singleton() {}
   public static Singleton Instance
         if (instance == null)
            instance = new Singleton();
         return instance;

Open in new window


Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would…
The video will let you know the exact process to import OST/PST files to the cloud based Office 365 mailboxes. Using Kernel Import PST to Office 365 tool, one can quickly import numerous OST/PST files to Office 365. Besides this, the tool also comes…
From store locators to asset tracking and route optimization, learn how leading companies are using Google Maps APIs throughout the customer journey to increase checkout conversions, boost user engagement, and optimize order fulfillment. Powered …

587 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question