Some time ago, someone asked me why the following doesn’t work in C#:

List<BaseType>myList = new List<DerivedType>

As I didn’t know this either, I turned to google and came across a very interesting blog from Rik Byers explaining the reasons behind this some more. Today, I noticed a related posting where
Rik shows a workaround for a very common usage of this type of conversion, namely passing a generic list of some derived type to a method that expects a list of the base type. The following won’t work

public int DoSomething(List<BaseType> list) {
    foreach (BaseType element in list) {
        ...
    }
}

Using a generic method, you can still accomplish the same effect though:

public int DoSomething<T> (List<T> list) where T: BaseType {
    foreach (BaseType element in list) {
        ...
    }
}

About these ads