No. While C # 4.0 introduces the concept of variance for interfaces, it cannot (and cannot) do what you are asking specifically.
In C # 4.0, you can do this:
IEnumerable<object> foo = new List<int>();
blow>
Edit: As Mark points out, this cannot be done with type values and reference types. However, since I think your question was more about generalized A:B
than about int:object
, I think this point carries. To be precise, I mean that C # 4.0 will allow something like this:
IEnumerable<object> foo = new List<string>();
But you cannot do what you describe. Namely, consider:
List<int> foo = new List<int>();
List<object> bar = foo;
bar.Add("baz");
Now what happens when we try to access foo[0]
? You have now violated the type safety of the list.
a source
to share