What happens if I initialize an array to size 0?

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.

Leave a Comment

deneme bonusu veren sitelerbahis casinomakrobetceltabetpinbahispolobetpolobet girişpinbahis girişmakrobet girişpulibet girişmobilbahis girişkolaybet giriş