A General Generics Question -- Don't Fight The Compiler

I've got a pretty firm grasp on generics such as when to use them, why they are useful, etc. I'm with the rest of the .Net camp when I echo how extremely useful they are. I've also learned that if you're fighting the compiler on generics for more than a few minutes, there is a reason as to why what you are doing is wrong.

The above held true until earlier today when I was left scratching my head over some code that IMO should have compiled just fine. Nothing explains coding problems better than code, so here goes an attempt at an explanation.

I have the following class declaration: 

public class ChannelViewChangedEventArgs<T> : ViewChangedEventArgs<T> where T: ChannelCollection<IChannel>

And this class declaration:

public class ChannelView<T> : ContentView<T>, IChannelView<T> where T : class, IChannel, new()

Later on in the ChannelView class I try to new up the ChannelViewChangedEventArgs like so:

new ChannelViewChangedEventArgs<ChannelCollection<T>>(new ChannelCollection<T>())

The compiler then complains that ChannelCollection<T> must be convertible to ChannelCollection<IChannel>. This isn't an option as it removes the benefits of generic type parameters, and seeing as T is of type IChannel I'm a bit confused as to why it won't compile. Then again it's also late at night so if the reason as to why is something obvious I won't be surprised at all. As stated above, if I'm fighting the compiler on something, I'm usually doing something wrong from a design standpoint.



# Robert McLaws said:

One thing to keep in mind is that Generics don't work for inherited classes. Using the ProviderModel as an example, you can't have a Generic List of System.Configuration.Providers.ProviderBase and add items that inherit from that class to the list. It worked in earlier betas of .NET 2.0, but was removed from the final version.


Thursday, May 24, 2007 12:22 PM