Had a problem in a complex linq query so I simplified it in LINQPad:
void Main()
{
List<basetype> items = new List<basetype>()
{
new typeA() { baseproperty = "1", extendedproperty = 1 },
new typeB() { baseproperty = "2", extendedproperty = 1.1 },
new typeA() { baseproperty = "3", extendedproperty = 1 },
};
items.Dump();
(from typeA item in items
where item is typeA
select item).Dump();
}
public abstract class basetype
{
public string baseproperty { get; set; }
public string type { get; set; }
}
public class typeA : basetype
{
public int extendedproperty { get; set; }
public typeA() { type = "A"; }
}
public class typeB : basetype
{
public double extendedproperty { get; set; }
public typeB() { type = "B"; }
}
The first Dump works fine and returns:
extendedproperty baseproperty type 1 1 A 1.1 2 B 1 3 A
However the second Dump errors with:
InInvalidCastException: Unable to cast object of type 'typeB' to type 'typeA'.
I can fix this by just removing the "typeA" but I wouldn't want to do that in the original statement as I would have to cast the type all over the place:
from item in items
Interestingly enough, moving the where also fixes this though you might agree that's a bit ugly:
from typeA item in items.Where(i => i is typeA)
My question is: why is the original where not filtering out the invalid item before the cast is evaluated?