C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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.
NullEmpty: 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 ArrayC# 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
}
}
}
Quote: String and Array properties should never return a null reference. Null can be difficult to understand in this context.
Arrays: microsoft.comAnd: This results in more reliable and simpler software, with the only downside being a null check in the property.