Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 510
  • Last Modified:

C# Singleton question

Hi Experts,
I would like to use a Singleton, but, kind of contradictingly, I'd like to use the Singleton sometimes, and also be able to create a new instance of the same class.  I have the following code that creates a Singleton.  Is there a way to modify this so that I can create a new one?

Thanks!
Mike
public sealed class Singleton
{
    static readonly Singleton instance=new Singleton();

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton()
    {
    }

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }
}

Open in new window

0
thready
Asked:
thready
  • 2
1 Solution
 
RGBDartCommented:
just make your private constructor - public.
You'll keep your static instance of this class, but will be able to create another one by calling constructor.

The question is - how when you need to create new instance? Do you want to call Singleton.Instance and sometimes get a new instance?
If yes, I'll suggest you to implement Lazy Load pattern and ClearCache() method...
0
 
RGBDartCommented:
Doh,spelling mistakes

The question is - when you need to create new instance?
0
 
threadyAuthor Commented:
Thank you.
0
 
jdavistxCommented:
It would appear that you don't need a singleton at all.  One, if not the(?), purpose of a singleton is that it's designed such that only a single instance of itself is ever created/used.  If you re-initialize the instance, then by definition your object is not a singleton but instead you just have some psuedo-static class that's probably difficult to understand and correctly use.

There are few places where the singleton pattern is the correct one.  The most common example is some kind of logging utility that doesn't necessarily impact your program, but instead it just logs output.  It doesn't interact with the rest of your code.

Most of the time, when you find yourself thinking, "A singleton will solve this problem!," all you really need is just a static class.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now