Josh Heyse

Thoughts Defragmented

Archive for June, 2008

Dictionary & Collection Initializers

Posted by jheyse on 18th June 2008

I’ve been working with the 3.5 Framework pretty much exclusively for last 3 months and I just recently ran across one of the new features that I some how missed, Dictionary & Collection Initializers.

Before the C# 3.0 the only collections you could initialize in-line where arrays.  This always left me doing things like:

List<string> list = new List<string>(new string[] { "Cubs", "Sox" });

Now, you can use the same syntax to declare non-array collections as well as dictionarys. Declaring the same collection now looks like this:

List<string> list = new List<string>() { "Cubs", "Sox" };

Collection initializers are great and all, but using this on dictionarys is really cool especially when I am prototyping abstract service factories and I don’t want to have to declare a static method to initialize the dictionary.  I wrote this piece of code today and was amazed at how clean it looked:

public static class ServiceFactory
{
    private static Dictionary<Type, Type> ServiceDictionary = new Dictionary<Type, Type>()
    {
        {typeof(IValidateAddress), typeof(USPS.AddressValidationService)},
        {typeof(ICityStateLookup), typeof(USPS.CityStateLookupService)}
    };
 
    public static TService CreateService<TService>()
        where TService : IService
    {
        TService service = (TService)Activator.CreateInstance(ServiceDictionary[typeof(TService)]);
        service.Initialize();
        return service;
    }
}

Posted in .NET, C# | No Comments »