Home
C#
Property Array Example: Return Empty Array
Updated Apr 7, 2022
Dot Net Perls
Array property. In C# programs, code that returns an array from a property is often problematic. We develop a reliable array property that avoids errors in foreach-loops.
Design pattern. Microsoft suggests a design pattern that does not use the null value, even when there is no data. So an empty array is returned when no elements are present.
Array
Property
Example. Here we simplify code that returns string arrays. If you have a 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 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.
null
NullReferenceException
Detail This property could have code that checks a backing field each time, and if the field is null, returns the empty array.
null Array
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 } } }
Discussion. In the Microsoft document Array Usage Guidelines, it is suggested that null array references not be returned, even when the backing store is null.
String and Array properties should never return a null reference. Null can be difficult to understand in this context.
Summary. For more reliable code, we can return an empty array from a property. When users of this property try to use the foreach-loop on the empty array, no exception will be thrown.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Apr 7, 2022 (edit link).
Home
Changes
© 2007-2025 Sam Allen