Home
C#
Property Array Example: Return Empty Array
This page was last reviewed on 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 7, 2022 (edit link).
Home
Changes
© 2007-2024 Sam Allen.