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?
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.