
Array properties often cause errors. There is a way to develop a reliable array property that will avoid causing errors in foreach loops. The MSDN documentation suggests a specific design pattern that does not use the null value, even when there is no data.

Here we see an interesting way to simplify your 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.
Property ExamplesThis C# example program uses an array property. It uses an empty string array.
Program that demonstrates array property [C#]
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
}
}
}
Output
No output.
Description. The above code demonstrates that when you loop over an empty string array, you will simply never execute the loop contents. If you instead had Empty return null, you would hit the NullReferenceException. This could make your code more complex.
More practical usage. The Empty property above might do some kind of processing before it decides to return the empty array of zero length. You might have code that checks a backing field each time, and if the field is null, returns the empty array.
Null Array Use
Let's look at MSDN and see what the usage guidelines for the .NET Framework are. In the document Array Usage Guidelines, it is suggested that null array references not be returned, even when the backing store is null. The example in this article could solve the problem shown in the section "Returning Empty Arrays".
MSDN referenceString and Array properties should never return a null reference. Null can be difficult to understand in this context. MSDN

We looked at how you can return an empty array from a public property in your C# program. When users of this property try to use the foreach loop on the empty array, no exception will be thrown, and the code in the foreach loop will not execute. This results in more reliable and simpler software, with the only downside being a null check in the property.
Array Types