I would like to know the reason that does not allow this type of convertion. The subject was already approached in this post in SO, but I want the low level explanation on why this is not possible natively.
Why does these casts fail?
OBS: I know it is possible to do so by reflection.
IList<People> peopleList = new List<People>()
{
new People() { Name = "Again", Age = 10 },
new People() { Name = "Over", Age = 20 },
new People() { Name = "Jonh", Age = 30 },
new People() { Name = "Enzo", Age = 40 },
};
var anonymous = (from p in peopleList
select new
{
Name = p.Name,
Age = p.Age
});
// Does not work
IList<People> listt = (IList<People>)anonymous;
//Does not Work
IList<People> listt = (anonymous as List<People>);
Peopleinstance. There's no conceivable cast from one to another. Cast means "treat this object as if it were that other equivalent type". There's nothing that says this anonymous type is equivalent toPeople. What if you used it to represent pets?Peopleand there is no conversion between these two types. Why should that cast work? How should the compiler know how to convertPeopleto your anonymous type? And even if it does, aIList<sometype>still is a totally different type thanIList<People>.