Generic Singleton - any suggestions?

A

Andrew Ducker

I want to make a whole bunch of classes into singletons. They all
descend from a base class.

I'd like to have code in the base class along the lines of :
private This(){ }
private static readonly This instance = new This();
public static This Instance
{
get
{
return instance;
}
}

but there's no way to get the type of the current class and use that
as the equivalent of a generic.

Any suggestions?

Andy
 
M

Marc Gravell

Jon Skeet's article on implementing a singleton can easily be
adapted to use generics. Just make sure that the type T has a
constraint of new so that you can create the instance.

But if it qualifies for "new()", I'm not sure you can really say it is
a singleton in the strictest sense - just that there is a static
instance available.

Marc
 
A

Andrew Ducker

But if it qualifies for "new()", I'm not sure you can really say it is
a singleton in the strictest sense - just that there is a static
instance available.

Yeah, that was my problem. I could do all of it bar enforcing it
being an actual singleton.

Andy
 
J

Jon Skeet [C# MVP]

Andrew Ducker said:
Yeah, that was my problem. I could do all of it bar enforcing it
being an actual singleton.

I don't believe there's any way of achieving what you want particularly
easily.

However, you can make the singleton pattern *really* short by using a
field rather than a property:

public class Singleton
{
public static readonly Singleton Instance = new Singleton();

Singleton(){}
}

As it's read-only, it's not violating encapsulation very much. You
can't use it for databinding, or put a breakpoint on it, but many of
the other disadvantages of exposing fields don't really apply. (As an
example of this being done in the framework, String.Empty is a field.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top