"Instead of 'null', return an empty collection such as 'Enumerable.Empty<method.ReturnType>'"
If your method returns an enumerable, then you should always return an empty list instead of null. In this way you eliminate the risk of a NullReferenceException
and You don't have to check for null in client code, so your code becomes shorter, more readable and easier to maintain.
For example, if a user tries to use it with foreach
or Linq
, it won't crash, but will just "skip" the loop (since there are no elements). Further reading.
public static IEnumerable<Payment> MyMethod()
{
if()
{
//return IEnumerable<Payment>
}
else
return null;
}
should be 🡻
public static IEnumerable<Payment> MyMethod()
{
if()
{
//return IEnumerable<Payment>
}
else
return Enumerable.Empty<Payment>;
}