AnsweredAssumed Answered

Error in Face selection code

Question asked by Alone A. on May 19, 2016
Latest reply on May 23, 2016 by Alone A.

Hi everyone

I try the code available on solidworks API and try to convert it into C# but I am getting error as "NullReferenceException is unhandled"

Can anyone help me to convert this VBA code to C#

 

Original Code:

'*****************************************************************

Option Explicit

Sub main()

    Dim swApp               As SldWorks.SldWorks

    Dim swModel             As SldWorks.ModelDoc2

    Dim swSelMgr            As SldWorks.SelectionMgr

    Dim swSelData           As SldWorks.SelectData

    Dim swPart              As SldWorks.PartDoc

    Dim swBody              As SldWorks.Body2

    Dim swFace              As SldWorks.Face

    Dim swEnt               As SldWorks.Entity

    Dim bRet                As Boolean

    Dim vBodies             As Variant

 

    Set swApp = CreateObject("SldWorks.Application")

    Set swModel = swApp.ActiveDoc

    Set swPart = swModel

    Set swSelMgr = swModel.SelectionManager

    Set swSelData = swSelMgr.CreateSelectData

    vBodies = swPart.GetBodies2(swAllBodies, True)

    Set swBody = vBodies(0)

   

    Set swFace = swBody.GetFirstFace

    swModel.ClearSelection2 True

   

    Do While Not swFace Is Nothing

        Set swEnt = swFace

        ' Select through Entity

        bRet = swEnt.Select4(True, swSelData): Debug.Assert bRet

        Set swFace = swFace.GetNextFace

    Loop

swModel.ClearSelection2 True

End Sub

'********************************************************************************

 

My Code:

 

Following code is followed by series of codes

//****************************************************************

                Face2 swFace = null;

                Body2 swBody = null;

                //Face2 swFace = default(Face2);

                //Body2 swBody = default(Body2);

                Entity swEnt = default(Entity);

                bool status = false;

                SelectData swSelData = default(SelectData);              

                swFace = (Face2)swBody.GetFirstFace();                              // ERROR at line  "NullReferenceException is unhandled"

                swDoc.ClearSelection2(true);

                //swBody.GetFirstFace();

                while ((swFace != null))

                {

                    swEnt = (Entity)swFace;               

                    // Select using IEntity

                    status = swEnt.Select4(true, swSelData);

                    Debug.Assert(status);

                    swFace = (Face2)swFace.GetNextFace();

                }

                System.Diagnostics.Debugger.Break();

 

//**************************************************************************

Plz help me to remove this error. Is anything wrong with my code.

Outcomes