What happens if I initialize an array to size 0?
stuff
will be a reference to an array with length theList.Count
with all entries initialized to default(string)
, which is null
.
Why should it? It will just point to an array of size 0, which is perfectly valid.
I think the confusion here arises from the ambiguity of representing the absence of data either by an array of size 0 or a variable set to null (the same ambiguity exists for strings with an empty string or a string reference set to null). Both are valid ways to indicate such absence and it would arguably make more sense to have only one. Hence, on some databases (Oracle specifically) an empty string equals the NULL value and vices versa and some programming languages (I think, new versions of C# are one of them) allow to specify references to never be null, also eliminating said ambiguity.
This is fine code. You will get an Array object with zero items (allocations) in it.
It will create an empty array object. This is still a perfectly valid object - and one which takes up a non-zero amount of space in memory. It will still know its own type, and the count - it just won't have any elements.
Empty arrays are often useful to use as immutable empty collections: you can reuse them ad infinitum; arrays are inherently mutable but only in terms of their elements... and here we have no elements to change! As arrays aren't resizable, an empty array is as immutable as an object can be in .NET.
Note that it's often useful to have an empty array instead of a null reference: methods or properties returning collections should almost always return an empty collection rather than a null reference, as it provides consistency and uniformity - rather than making every caller check for nullity. If you want to avoid allocating more than once, you can use:
public static class Arrays<T>
{
private static readonly T[] empty = new T[0];
public static readonly T[] Empty { get { return empty; } }
}
Then you can just use:
return Arrays<string>.Empty;
(or whatever) when you need to use a reference to an empty array of a particular type.