I’ve noticed that several built-in classes/methods in .NET framwork takes an argument of System.Type where (in my opinion) it would have been cleaner to use generics.
For example, to create a DataContractSerializer instance I need to write
var s = new DataContractSerializer(typeof(MyCustomClass));
instead of
var s = new DataContractSerializer<MyCustomClass>();
I’m not looking for a debate on which way is the “best”, I’m rather curios to know whether there are any good reasons for doing either way. 🙂
Some more examples (taken from my head) are:
– System.Xml.Serialization.XmlSerializer (constructor)
– System.ServiceModel.ServiceHost (constructor and a couple of methods)
– System.Web.Mvc.ModelBinderAttribute
The first two classes in your example – XmlSerializer and ServiceHost – were designed before generics existed. Presumably Microsoft could invent replacements for these classes that deal in generics, but this hasn’t happened.
Generics often aren’t essential: if a method’s signature doesn’t depend on the type, then it shouldn’t make any difference to the caller whether they pass
typeof(MyCustomClass)or callMethod<MyCustomClass>. Having a System.Type argument is often more useful: if you’re writing your own reflection code, you’ll normally have a System.Type anyway. If all you’ve got is a System.Type, then calling a generic method is much harder.