For level order traversal why does this exception occur? Following exception occurs:
Cannot implicitly convert type \'
System.Collections.Generic
Pretty sure that if it compiles, doing a cast is a real bad idea. Here's why:
public class myStupidList : IList
{
//implementation unimportant
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var result = new List>();
IList> imNotAListofLists = (IList>)result;
imNotAListofLists.Add(new myStupidList());
//result is not a very valid variable right now, is it?
}
As mentioned in my comment, these types of collection issues boil down to covariance
and contravariance
, and .NET does provide a lot of tools for dealing with them. (Such as various read-only collections and interfaces)
..Which, explains why you get your error as well. There is no implicit cast from List
to List
because that cast cannot succeed without breaking type-safety. (and as @Grax mentioned, neither derives from the other)