Search code examples
c#if-statementout

Evaluate the result of a method and get its value, if true, without calling it again


I'm using ZWCad APIs and .NET, C#

I need to evaluate if two segments intersect.

There is a method that does this and returns an array of points.

So I'm evaluating if this method returns null. If it does, then the segments don't intersect. If segment intersects then I need the instersection to do wathever.

This is the code I have.

if(segment.IntersectWith(segmentoEixo)!=null)
{
    Point3d[] intersectionPoints = segment.IntersectWith(segmentoEixo);

    // do something with this points
}

So I'm calling the IntersectWith method to evaluate if the segments intersect and calling it again if the lines do intersect.

I've researched and tried the out keyword but got anywhere with that.

Is there any other way to make this without calling the method twice?

Thanks


Solution

  • Another option is through pattern matching:

    if (segment.IntersectWith(segmentoEixo) is Point3d[] intersectionPoints)
    {
        // do something with this points
    }
    

    If segment.IntersectWith(segmentoEixo) returns null, then the Point3d[] pattern will not be matched, and the condition will be false.

    This also takes care of the intersectionPoints variable assignment.