tags:

views:

81

answers:

3

I've been studying code of some different libraries, and notice that some will provide equivalent generic and non-generic functions in the same class.

One example is the IServiceLocator interface of the Common Service Locator project:

public interface IServiceLocator
{
    object GetInstance(Type serviceType);
    object GetInstance(Type serviceType, string key);
    IEnumerable<object> GetAllInstances(Type serviceType);

    TService GetInstance<TService>();
    TService GetInstance<TService>(string key);
    IEnumerable<TService> GetAllInstances<TService>();

}

The impression I get is that this is for maximizing accessibility, perhaps from COM. Absent those concerns, this seems like redundant code. Is there anything I'm missing?

+2  A: 

Probably because the generic type is better for syntax and users will prefer it since it can cast it to the correct type, but for example, if the type is looked up at run time using reflection, you can't use the generic option and need to use the one that takes a Type.

In addition, generics are always resolved at compile time. Think of it as using the generic one when you know the type at compile time, and the non-generic during runtime.

vcsjones
+6  A: 

Sometimes you know the type you need at compile time, at which point generics can give you compile-time safety and neater code.

Sometimes you only know the type you need at execution time, at which point generics become a pain in the neck, because you need to call them via reflection.

Providing both options gives the flexibility to handle both situations as well as possible.

Jon Skeet
A: 

The reason is the non-Generic will use an implied generics by checking its type so that you do not have to mention the type.

Aliostad