If I have an object which looks like:
class Person : IProxy
{
// Properties
}
And I have a method which returns an object which is actually a List<Person>:
object GetList()
{
List<Person> people = new List<Person>();
person.Add(new Person());
person.Add(new Person());
return people;
}
Why does the following code result in null?
var obj = GetList() as List<IProxy>;
But the code below returns a List:
var obj = GetList() as List<Person>;
In the Watch panel of Visual Studio, my type is reported as:
object {System.Collections.Generic.List<Person>}
A
List<Person>andList<IProxy>are two different types so converting one to another may yield null.will do what you want. You can also use
Personally I prefer OfType because it doesn’t throw an exception when the collection contains heterogeneous types
Covariance and Contravariance FAQ may answer more of your questions.