Home > Backend Development > C++ > Should Collection-Returning Methods Return Null or an Empty Collection in C#?

Should Collection-Returning Methods Return Null or an Empty Collection in C#?

Patricia Arquette
Release: 2025-01-25 15:06:11
Original
852 people have browsed it

Should Collection-Returning Methods Return Null or an Empty Collection in C#?

C# collection return value: return null or empty collection?

When writing the method of returning a collection, you often encounter a problem: Is it returning to NULL or returning to an empty collection? In C#, the best practice suggestion is always returned to the latter.

Returning NULL will bring potential problems. The code that depends on the collection may encounter air checks and abnormalities, resulting in unexpected behaviors. Consider the following example:

In order to avoid these problems, they always return to the empty collection. This can ensure that the code can handle the collection safely, regardless of its content.

For attributes, it is best to set it only once, and then keep it unchanged. Use the following mode:
<code class="language-csharp">if (myInstance.CollectionProperty != null) {
    foreach (var item in myInstance.CollectionProperty) {
        /* 此处可能出现问题 */
    }
}</code>
Copy after login

In .NET 4.6.1, it can be simplified to:

For the method of returning to enumerate type, you can easily return the empty available enumeration type instead of NULL:
<code class="language-csharp">public List<foo> Foos { get; private set; }

public Bar() { Foos = new List<foo>(); }</code>
Copy after login

The use of is more effective than returning an empty set or array created by the rewarded.
<code class="language-csharp">public List<foo> Foos { get; } = new List<foo>();</code>
Copy after login

The above is the detailed content of Should Collection-Returning Methods Return Null or an Empty Collection in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template