Skip to content

Latest commit

 

History

History
36 lines (29 loc) · 1.01 KB

GCop103.md

File metadata and controls

36 lines (29 loc) · 1.01 KB

GCop 103

"Instead of 'null', return an empty collection such as 'Enumerable.Empty<method.ReturnType>'"

Rule description

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.

Example

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>;
}