tags:

views:

707

answers:

2

While checking out the generic collection in .net i found about KeyedByTypeCollection. Although I worked with it and got to know how to use it, I did not get in which scenario it will be useful.

I read through ServiceProvider, cache etc. done with generics without cast, but could not get much.

I think, there must have a reason as to why it has been included in the .Net framework. Any body who have used the KeyedByTypeCollection can explain me why they used it or any body, if they know in which scenario potentially it can be used, can explain it to me.

As more of a curiosity does any other languages support this type of collection ?

+1  A: 

Hi,

a possible usage for this collection is decribed here:

http://en.csharp-online.net/WCF_Essentials%E2%80%94Enabling_Metadata_Exchange_Programmatically

The collection can at max contain one entry for each type because the type is the key. Thus it is useful to retrieve any kind of meta data associated with a type.

0xA3
+4  A: 

Hello Biswanath,

AFAIK, this generic collection serves just as a simple wrapper for KeyedCollection<KEY,VALUE> when KEY is the Type of the VALUE to store.

For example, it is very convinient to use this collection if you want to implement a factory returning singletons:

public class Factory<T>
{
    private readonly KeyedByTypeCollection<T> _singletons = new KeyedByTypeCollection<T>();

    public V GetSingleton<V>() where V : T, new()
    {
        if (!_singletons.Contains(typeof(V)))
        {
            _singletons.Add(new V());
        }
        return (V)_singletons[typeof(V)];
    }
}

The use of this simple factory would be something like the following:

    [Test]
    public void Returns_Singletons()
    {
        Factory<ICar> factory = new Factory<ICar>();
        Opel opel1 = factory.GetSingleton<Opel>();
        Opel opel2 = factory.GetSingleton<Opel>();

        Assert.IsNotNull(opel1);
        Assert.IsNotNull(opel2);
        Assert.AreEqual(opel1, opel2);
    }

Another usage for KeyedByTypeCollection<T> would be inside a service locator...

Prensen
Thanks, for the nice usage you have provided here.
Biswanath