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.
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.
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
.
string
array—this array could be cached in some programs.string
array, you will never execute the loop contents.null
, you would hit the NullReferenceException
. This could make your code more complex.null
, returns the empty 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 } } }
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.
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.