> You can use the singleton pattern with generics with no problem. For
instance:
using System;
using System.Text;
class Singleton<T> where T : class, new()
{
static T instance;
static object padlock = new object();
public static T Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
Console.WriteLine
("Creating instance of {0}", typeof(T));
instance=new T();
}
return instance;
}
}
}
}
I'm doing something along those lines. My goal is to create a template
collection that can hold any type that implements a certain interface.
The way it works now, each time I give the collection a different
type, that creates a new singleton for that type. If I keep calling
properties on the collection for that type, I always reference the
singleton. It's working just the way I want it to.
public class MetaCollection<TValue> : where TValue : IMyCollection,
new()
{
private static MyCollection<TValue> _instance;
public static MyCollection<TValue> Instance
{
get
{
if( _instance == null )
_instance = new MyCollection<TValue>( );
}
}
}
But I keep getting a new instance back when I do:
MyCollection<someclass> SomeClassColl =
MyCollection<someclass>.Instance;
rather than getting the singleton. If I access a property on the
collection:
MyCollection<someclass>.Instance.Fill();
MyCollection<someclass>.Instance.GiveMeFirstItem() ;
for example, the singleton works fine. For now, I just use the entire
syntax. All I'm trying to do is provide a shortcut to the Instance
syntax. Do you know how I can get the shortcut to work using syntax
similar to the above?
I have actually wrapped the Instance check code inside of the above
methods, which is shorter syntax since I don't have to do ".Instance".
Still, I want to understand why the first line mentioned doesn't give
back a singleton.
Thanks,
Brett