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>
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>
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>
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!