Search code examples
linqoftype

Linq - OfType<> not working as expected


I have the following code which detects all the elements in a Silverlight application beneath a certain point

then filters them to be only those of a particular type - CardButton

IEnumerable<UIElement> elementsBeneathCursor =
                VisualTreeHelper.FindElementsInHostCoordinates(new Point(xPosn, yPosn), Application.Current.RootVisual);
            IEnumerable<CardButton> cardsBeneathCursor = elementsBeneathCursor.OfType<CardButton>();

Even though when I inspect elementsBeneathCursor in the debugger, I can see there are 2 elements of type CardButton Yet when I apply the OfType<> filter the resultant list is null

what's going wrong?


Solution

  • The resulting list won't actually be null... but the sequence will be empty, if neither of those elements is actually a CardButton. Note that OfType doesn't perform any custom conversions, so if you were expecting those to happen, that may explain it.

    Try going through the unfiltered list and printing out the result of calling GetType on each element to see what it really is.