Let’s say I have a function like:
void myFunc(List<AClass> theList)
{
string[] stuff = new string[theList.Count];
}
and I pass in an empty list.
Will stuff be a null pointer? Or will it be a pointer to some random place in memory that is uninitialized?
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:
Then you can just use:
(or whatever) when you need to use a reference to an empty array of a particular type.