Unexplained suggestion that variable may be null

Answered

Hi,

 

Please help me understand the following suggestion;

 

private static IList<int> Merge2(IList<string> intervals)
{
string previous = null;

var list = new List<int>();

if (intervals == null || intervals.Count == 0 || intervals.Any(x => x == null))
{
return list;
}

foreach (var current in intervals)
{
previous = current;
}

// WHY ReSharper says that previous MAY BE null ?
list.Add(previous.Length);
// ^^^^^^^^^^^
return list;
}

 

 

0
2 comments
Official comment

Hi Dmitriy,

Richard's comment above is absolutely correct. ReSharper cannot perform an analysis of such a complex scenario.

So, you may ignore squiggles or, as a workaround you may consider any of the following options:
1. Add explicit null check. For example,
    if (previous != null) list.Add(previous.Length);
2. Disable bulb suggestion with Alt+Enter| Inspection: "Possible 'System.NullReferenceException | Disable once with comment | Disable once with comment

 

Probably because the control flow is too complicated to analyse in real-time. Try replacing the foreach loop with a simple access of the last item in the list:

var list = new List<int>();
if (intervals != null && intervals.Count != 0 && intervals.All(x => x != null))
{
string previous = intervals[intervals.Count - 1];
list.Add(previous.Length);
}

return list;

If it still thinks previous could be null, you can add a Debug.Assert(previous != null); line before the list.Add call to stop the warning.

0

Please sign in to leave a comment.