"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Should Methods Return Null or Empty Collections?

Should Methods Return Null or Empty Collections?

Published on 2025-01-26
Browse:963

Should Methods Return Null or Empty Collections?

Returning null or an empty collection: Best practices

When designing a method that returns a collection as the return value type, a question arises: should it return null or an empty collection? Best practice strongly recommends returning an empty collection in all cases.

Why choose empty collection?

Returning null is a bad practice because it leads to unnecessary code complexity and potential runtime errors. For example, if you return null for a collection property:

if(myInstance.CollectionProperty != null)
{
  foreach(var item in myInstance.CollectionProperty)
    /* 如果 CollectionProperty 为 null,此代码可能会失败 */
}

This code may cause an exception if myInstance.CollectionProperty is indeed null. Instead, it's better to return an empty collection, ensuring that the above code can still execute without errors.

Attribute Best Practices

For properties that return a collection, it is recommended to initialize the property only once. This can be done during the constructor of the class containing the property:

public List Foos { public get; private set; }

public Bar() { Foos = new List(); }

With C# 6, a more concise version is available:

public List Foos { get; } = new List();

Method Best Practices

For methods that return a collection, if the actual collection does not exist, an empty collection is returned. You can use Enumerable.Empty() method for this purpose:

public IEnumerable GetMyFoos()
{
  return InnerGetFoos() ?? Enumerable.Empty();
}

This approach ensures that even if InnerGetFoos() returns null, the method still returns an empty collection, preventing potential errors.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3