66

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?

2
  • 1
    It's quite useful when you need an empty IEnumerable<T> (usually for testing)
    – Skurmedel
    Jun 23, 2010 at 14:12
  • 8
    Enumerable.Empty<...> is even better. Jun 23, 2010 at 14:33

8 Answers 8

108

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.

13
  • 1
    The key point I was confused about was whether an empty array takes a non-zero amount of space, as you call it.
    – samoz
    Jun 23, 2010 at 14:23
  • 2
    As the information about its 'emptyness' has to be stored somewhere (i.e. the count) it has to take up some space. Given what I wrote in my answer, you could of course (but this is dangerous) have the internal guidline that instead of initializing arrays of length 0 you set the reference to null. But this may need some additional checks when such arrays are used and not be worth the slim space savings. Jun 23, 2010 at 14:26
  • 5
    @NETscape: well what would you do if you were implementing a method returning an int[] and you didn't have any elements to return?
    – Jon Skeet
    May 23, 2014 at 19:35
  • 4
    @NETscape: returning null is a pain for all callers. Returning an empty array gives a much more consistent, uniform experience. You can always stash a reference to an empty array to avoid allocating it each time you need to return one....
    – Jon Skeet
    May 23, 2014 at 19:46
  • 1
    @Pac0: If you can use Array.Empty, use that instead of any of the code from this answer. It didn't exist in 2010 though :)
    – Jon Skeet
    Jan 28, 2019 at 12:25
12

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.

11
  • 1
    "Both indicate the absence of data and there is no right or wrong way to indicate such absence." But conceptually, there usually is a difference between the two. It's like the difference between having an empty cardboard box and not having a box at all. (I hope I never have to work with databases where "" == NULL, as I would get quite confused by that.)
    – JAB
    Jun 23, 2010 at 14:19
  • Oracle apparantly does. I also don't 100% agree with that, because of terinary logic (IS NULL vs = NULL). Jun 23, 2010 at 14:22
  • 3
    NULL == "" is an evil Oracle "feature" - no sane system should generally treat them as equal. My opinion...^^ Jun 23, 2010 at 14:23
  • 5
    In a database, NULL generally means "this value is unknown". So MIDDLE_NAME IS NULL indicates the middle name is unknown, while MIDDLE_NAME = '' means this person is known to have no middle name. In C#, the semantics of null are much wider (not applicable, not yet set, etc.), but empty strings and arrays would indicate—to me anyway—that the value has been determined to be empty. (Sometimes in a database NULL means "not applicable", but that irritates the hard-core RDBMS theorists. Use with caution.) Jun 23, 2010 at 18:26
  • 1
    @JeffreyLWhitledge In Oracle, '' IS NULL is TRUE. So be careful what you say about databases in general...
    – ErikE
    Jan 29, 2016 at 0:06
5

This is fine code. You will get an Array object with zero items (allocations) in it.

3

stuff will be a reference to an array with length theList.Count with all entries initialized to default(string), which is null.

2
  • 1
    His point was that you pass an empty list to it, i.e. theList.Count is 0. This of course means that there won't be any entries initialized to anything. Jun 23, 2010 at 14:12
  • 5
    In which case it will be a reference to an array with length 0 with all 0 entries initialized to null. ;)
    – dahlbyk
    Jun 23, 2010 at 14:14
2

The following is in the C# language specification:

  • The computed values for the dimension lengths are validated as follows. If one or more of the values are less than zero, a System.OverflowException is thrown and no further steps are executed.
  • An array instance with the given dimension lengths is allocated. If there is not enough memory available to allocate the new instance, a System.OutOfMemoryException is thrown and no further steps are executed.

So for a length of zero, memory is allocated.

1

If theList is an actual List object, and is merely empty, then theList.Count is going to return 0. Which means that the declaration becomes

string[] stuff = new string[0];

In other words, stuff will just be an array (of strings) with length 0.

3
  • 1
    No, stuff will be an empty array of strings, not an empty string. Jun 23, 2010 at 14:12
  • I'm pretty sure stuff is an array of strings, not a string!? Jun 23, 2010 at 14:13
  • 1
    @Eric: I know, I got string mixed up with char and was thinking in C/C++ terms (thinking too fast has always been one of my failures). Corrected my answer before I even saw your comment.
    – JAB
    Jun 23, 2010 at 14:14
1

Linq .Concat will throw an exception if any of the arguments is null(which can occur in my case). So I had to do something like this in my code:

public string[] ConcatUsers(string[] users1, string[] users2)
{
    return (users1 ?? new string[0]).Concat(users2 ?? new string[0]).ToArray();
}

(just an example where 0-size array initializer could be useful)

0

As long as you ensure that your List<> that you actually pass in to the method was initialized somewhere, like

List<Stuff> myStuff = new List<Stuff>;

the list will not point to null. It will be a list of zero Stuffs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.