C# Array Property, Return Empty ArrayUse an array property. Return an empty string array instead of null.
dot net perls
Array properties often cause errors. We develop a reliable array property that avoids errors in foreach-loops. Microsoft suggests a design pattern that does not use the null value, even when there is no data.
Example. Here we simplify code that returns string arrays. If you have a method or property that returns null and you use that result in a foreach-loop, your program will throw a NullReferenceException.
However You can instead return an empty string[0] array. This array could be cached in some programs.
Info The code shows that when you loop over an empty string array, you will never execute the loop contents.
Tip If you instead had Empty return null, you would hit the NullReferenceException. This could make your code more complex.
Empty This property could use logic. You might have code that checks a backing field each time, and if the field is null, returns the empty array.
Null Array
Discussion. Let's look at Microsoft Docs and see the usage guidelines. In the document Array Usage Guidelines, it is suggested that null array references not be returned, even when the backing store is null.
C# program that demonstrates array property
class Program { static void Main() { foreach (string item in Empty) { System.Console.WriteLine(item); // Never reached } } /// <summary> /// Get an empty array. /// </summary> public static string[] Empty { get { return new string[0]; // Won't crash in foreach } } }
Summary. We looked at how you can return an empty array from a public property in a C# program. When users of this property try to use the foreach-loop on the empty array, no exception will be thrown. The code in the foreach-loop will not execute.
And This results in more reliable and simpler software, with the only downside being a null check in the property.
Array usage guidelines:
String and Array properties should never return a null reference. Null can be difficult to understand in this context.
© 2007-2021 sam allen. see site info on the changelog