Exception while iterating over view components.(type cast issue ? )

Hi all,

I have a view which essentially contains few sub assemblies and parts. My eventualy goal is to create detailed view for few specific parts -if they have a specified property match.

So in essence i am iterating over the view components and trying to find each part and checking against the properties. While tyring to do that i am getting exception when i try to typecase the drawingComponent into Component2.

DrawingComponent swRootDrawComp = (DrawingComponent)swViewSection.RootDrawingComponent;

object[] vDrawChildCompArr2 = swRootDrawComp.GetChildren();

foreach (var vDrawChildComp in vDrawChildCompArr2)

                {

                    Component2 swComp = null;

                    DrawingComponent swDrawComponent = vDrawChildComp as DrawingComponent;

                    if (swDrawComponent != null && swDrawComponent.Component != null)

                       swComp = swDrawComponent.Component as Component2;

                    if(swComp != null)

                    {

...............

I am getting exception at this highlighted line and have no clue why. My thoughts so far has been circling around that since  the main view has some sub assemblies the cast is failing. Can someone please help me around what checks should i be enforcing to avoid getting the exception ?

SolidworksApi macros