tags:

views:

104

answers:

3

I don't want that end programmer can user == or != operator against my singelton class.

End user can't do

if( SingleInstace == null)

I have overloaded != and == operator but it doesn't help.

I have a scenario in which I want to dispose of the singleton instance and initialize it with different parameter. For example my singelton instance is DBAccess and I want to intialize it with different server name. Therefore in between the calls of disposing of the singleton instance and intialize it with different server name ; there may be call of null check. In that case my singelton instance will be initialize with old server name.

Please help!!

+4  A: 

SingleInstance should be private inside the Singleton class, so that nobody can access it outside of the class's "GetInstance" method.

Nellius
I'm pretty sure SingleInstance is the public property that you normally use in place of a getter method in C#, not the backing field. Also the client programmer will still be able to compare the return value from the property/method to null, which is what the OP asked.
Jonas H
+5  A: 

It is pointless to prevent this. The client code can always cast it to object.

Hans Passant
Thanks for the ans. Please see my updated query.
Ashish Ashu
A: 

To implement your singleton, you'll use something like this:

class HasSingleton
{
    static public HasSingleton Instance {
        get 
        {
            if (_instance==null)
            {
                _instance=new HasSingleton();
            }
            return _instance;
        }
    static private _instance;
}

That way, you will never be able to get null for

HasSingleton.Instance

I omitted locking code for brevity.

Daniel Mošmondor