Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is System.Type arguments chosen over generics in some classes of .NET framework?

Tags:

.net

generics

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

like image 277
Ozzy Avatar asked Jun 07 '11 13:06

Ozzy


1 Answers

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.

like image 66
Marc Gravell Avatar answered Sep 23 '22 16:09

Marc Gravell