DEV Community

Cover image for Avoid returning null collection
Shreyans Padmani
Shreyans Padmani

Posted on

Avoid returning null collection

In C#, when returning a collection from a method, never return null. Instead, always return an empty collection like Enumerable.Empty().

Returning null from methods that return collections is a common but risky practice in C#. It forces the caller to write additional null checks and increases the chance of runtime errors like NullReferenceException.

Image description

Benefits:

  • Eliminates unnecessary null checks
  • Prevents runtime exceptions
  • Promotes cleaner and safer code

Conclusion

Returning null from methods that return collections can lead to unnecessary null checks and potential runtime errors. Instead, always return an empty collection using Enumerable.Empty(). This approach makes your code cleaner, safer, and more predictable—leading to fewer bugs and better developer experience.

Small change, big impact. Start using empty collections over null today.

Top comments (0)