Avoid returning null collection
Shreyans Padmani

Shreyans Padmani @shreyans_padmani

About: CTO & Co-Founder passionate about helping startups scale through AI, Cloud, and product innovation. Experienced in C#, .NET Core, Blazor, and AWS. Excited to connect at GITEX 2025.

Location:
USA
Joined:
Feb 22, 2025

Avoid returning null collection

Publish Date: Jun 8
1 0

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.

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.

Comments 0 total

    Add comment