Search code examples
c#ienumerableoftype

OfType preforms cast instead of filter


Let's say in my database I have 2 classes: Class FooBar and Class BarFoo. I perform a query on my database which returns class FooBos which contains a list of FooBar BUT the list can contain instances of BarFoo(don't ask me why , this how i got the database and i can't edit it).

Anyway to build my Domain object I do a check to see which class is which using following code

if(FooBos.FooBars.OfType<BarFoo>().Count() != 0)
  //Do things for FooBar here
else
  //Do Things for BarFoo here

So the problem is after the OfType the entire list is of the Type BarFoo and i can't seem to figure out why.

Anyone knows why this happens ?


Solution

  • Generally, OfType<> is employed whenever an inheritance relation exists. In your case, I suspect that FooBar is a child of BarFoo.

    If this is the case then it means all of your objects in the list is either inherit BarFoo or they are just BarFoo objects; so OfType<BarFoo> returns all objects.