Solved

Type intializer error on Singleton class

Posted on 2008-06-15
2
677 Views
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."}

    }
0
Comment
Question by:AdibRahman77
2 Comments
 
LVL 12

Expert Comment

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

Accepted Solution

by:
anarki_jimbel earned 500 total points
ID: 21789775
Your implementation is wrong. You maty find classic implementation on msdn:
http://msdn.microsoft.com/en-us/library/ms998558.aspx.

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
   {
      get 
      {
         if (instance == null)
         {
            instance = new Singleton();
         }
         return instance;
      }
   }
}

Open in new window

0

Featured Post

How our DevOps Teams Maximize Uptime

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us. Read the use case whitepaper.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

840 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