Friday, April 18, 2008

Generic Gripes

Two things:

1. If you have a generic class with type parameter constraints, those contraints are not inherited automatically in sub types. Ex:

class Foo<T> where T: IConvertible
{
}

class Bar<T> : Foo
{
}

Don't work. You have to put the "where T: IConvertible" on Bar. Doesn't make sense to me.

2. There is no way to loop through a bunch of generic instances with different type parameters and access members that don't have type parameters anywhere in their signature. Ex:

If you have some lists, like:
List<int> = GetInts();
List<strings> = GetStrings();

You can't reference them with just List<> or List<?> or something. While obviously
you can't access the Add, Insert, indexer, and whatever else has the generic type in it. But it would be really convenient if I could access things that don't use it, like Count.

It would be cool to be able to do something like this:

using the two lists above:

List<List<?>> lists = List<List<?>> (ints, strings);

foreach( List<?> currList in lists )
{
int count = currList.Count;//Add would not be available. But Clear would.
}

In the List case, IList makes it possible to loop through some lists and get the Count. So maybe that's a bad example. But imagine you make your own sweet generic class, and want to access some generic-agnostic member, like the HasValue property of Nullable<T>. Then you have to implement an interface or derive from a base class that isn't generic.

I understand why that's not possible today and that it would be difficult to allow. However, it's not impossible and would be nice.

That's all. Very granular crap. Nice weather today.

No comments: