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
In the case of XmlSerializer
, it pre-dates generics, which is a good reason - but there are others. Having spent a lot of time on serialization code, I know painfully that (very common in library code) often all you have is the Type
. Simply, library code like WCF can't be generic throughout - it would be a lot of overhead and complexity. For example, it might have just looked up the Type
from the element-name (or some other marker). It didn't know the type in advance, so it can't possibly be "generic" (in the <T>
sense).
In those cases when you have a Type
, you can use MakeGenericMethod
etc, but that is a lot of overhead, and can actually break CF etc (you start getting missing-method errors eventually).
As it happens, I have recently rewritten an entire serialization library from using generics as the primary API to using Type
as the primary API. Fortunately this means the old methods just use typeof(T)
with the new methods, so it works nicely.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With