Parasoft not recognizing custom IEnumerable extension method .IsNullOrEmpty()

114 views Asked by At

We have a custom extension method .IsNullOrEmpty() that does exactly what it sounds like it does.

public static bool IsNullOrEmpty<T>(this IEnumerable<T> target)
{
  bool flag = true;
  if (target != null)
  {
    using (IEnumerator<T> enumerator = target.GetEnumerator())
    {
      if (enumerator.MoveNext())
      {
        T current = enumerator.Current;
        flag = false;
      }
    }
  }
  return flag;
}

However, parasoft does not recognize this as a valid null check and it gives a

BD.EXCEPT.NR-1: Avoid NullReferenceException

soon after the extension method is used.

Example:

IEnumerable<Foo> foos = _repo.GetFoos();
IEnumerable<Bar> bars;

if (!foos.IsNullOrEmpty())
{
    bars = foos.Select(foo => foo.Bar);  // This is where the Parasoft violation would occur.
}

Is there a way to get Parasoft to recognize our extension method?

1

There are 1 answers

6
Ctznkane525 On

If the target is null, you cannot call a method on it, it'll bomb.

You need the null check still.

if (foos != null && !foos.IsNullOrEmpty())
{
    bars = foos.Select(foo => foo.Bar);  // This is where the Parasoft violation would occur.
}

The other approproach would be to create a function to check it is has data instead (the opposite of your function), then you could call the ? operator on the null object and the boolean would return FALSE in that case which would be desirable.

if (foos?.Any())
{
    bars = foos.Select(foo => foo.Bar);  // This is where the Parasoft violation would occur.
}