This error is because .Results
is null
, yet you're trying to call the GetCircle()
method on it.
One way to handle this is to use the null-conditional operator (?.
), which returns null
if the left hand side is null, otherwise continues with the method or property on the right hand side:
// If Results is null, the call to GetCircle will not happen, and the result will be null
// Not needed on the second condition, since '&&' would return 'false' right away
if ((CogFindCircleTool_.Results?.GetCircle() != null) &&
(CogFindCircleTool_.Results.GetCircle().Visible == true))
You could shorten your code even further by adding another .?
when accessing the Visible
property, and then we don't need to explicitly check for .GetCircle() != null
first.
Below, if Results
is null
or GetCircle
returns null
, the expression will fail (because null != true
), otherwise the condition Visible == true
will be evaluated:
if (CogFindCircleTool_.Results?.GetCircle()?.Visible == true)
In the comments you stated that you have a line like this inside the if
statement:
Label.SetXYText(CogFindCircleTool_.Results.GetCircle().CenterX,
CogFindCircleTool_.Results.GetCircle().CenterY, "(" +
Math.Round(CogFindCircleTool_.Results.GetCircle().CenterX, 3).ToString() +
"," + Math.Round(CogFindCircleTool_.Results.GetCircle().CenterY, 3).ToString() + ")");
One thing to improve performance is to capture the result fo the GetCircle()
method once rather than calling it over and over again, which takes extra processing cycles. This will also make the code shorter and more readable. You can also use string interpolation instead of concatenation to shorten the code a little more.
You also mentioned that you were still getting a null reference exception on the inner line, which could only mean that Label
is null (from what I can tell). If so, we could use the ?.
operator when calling the SetXYText
method:
// Capture the result of GetCircle() once
var circle = CogFindCircleTool_?.Results?.GetCircle();
if (circle?.Visible == true)
{
Label?.SetXYText(circle.CenterX, circle.CenterY,
$"({Math.Round(circle.CenterX, 3)},{Math.Round(circle.CenterY, 3)})");
}
Note that the code above will not do anything if something is null. If you want to do something else if circle
is null
or Label
is null
, then you should explicitly check that rather than use the ?.
operator:
if (circle == null)
{
// do something if circle is null
}
else if (circle.Visible == true)
{
if (Label == null)
{
// do something if Label is null
}
else
{
Label.SetXYText(circle.CenterX, circle.CenterY,
$"({Math.Round(circle.CenterX, 3)},{Math.Round(circle.CenterY, 3)})");
}
}