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

127 Views Asked by At

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

3

There are 3 best solutions below

0
Johnathan Barclay On BEST ANSWER

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.

1
fvu On

I may be missing the point completely, but why no do:

Point3d[] intersectionPoints = segment.IntersectWith(segmentoEixo);
if(intersectionPoints != null)
{
    // do something with this points
}

Explanation: instead of using a call just to check if there are no intersections, already store the result of that test, and work with the result if it's not equal to null

3
Fildor On

Just additional to fvu's answer, that I absolutely second, and because you mentioned an attempt using the out keyword:

public bool TryIntersect(LineSegment3d segment, LineSegment3d segmentoEixo, out Point3D[] intersection)
{
    intersection = segment.IntersectWith(segmentoEixo);
    return intersection != null;
}

should work like this:

if ( TryIntersect( segment, segmentoEixo, out var intersection ) )
{
   // work with intersection here...
}

or as extension:

public static bool TryIntersectWith(this LineSegment3d segment, LineSegment3d segmentoEixo, out Point3D[] intersection)
{
    intersection = segment.IntersectWith(segmentoEixo);
    return intersection != null;
}

should work like this:

if ( segment.TryIntersectWith( segmentoEixo, out var intersection ) )
{
   // work with intersection here...
}