62

If an array is empty, it looks like you can't check it's length using ".length". What's the best way to check if an array is empty?

sooprise
  • 20,955
  • 62
  • 180
  • 265

13 Answers13

154

You can absolutely check an empty array's length. However, if you try to do that on a null reference you'll get an exception. I suspect that's what you're running into. You can cope with both though:

if (array == null || array.Length == 0)

If that isn't the cause, please give a short but complete program demonstrating the problem. If that was the cause, it's worth taking a moment to make sure you understand null references vs "empty" collections/strings/whatever.

Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929
  • In what situation would an array have .Length == 0? An array dimensioned to size 0? – sooprise Jul 09 '10 at 14:09
  • 44
    The important thing to note about the code above is that in csharp, the or operator (`||`) is short circuiting. It sees that the array is null (statement is true) and does NOT attempt to evaluate the second statement. If it did, you'd still get a NullReferenceException and would have to nest your if statements. Not all languages are like this, VB.Net being one example. The default `Or` operator is NOT short-circuiting; they have `OrElse` for that. http://support.microsoft.com/kb/817250 – Tim Coker Jul 09 '10 at 14:16
  • @Tim, wow, that's interesting thanks for posting that tip. I learn something new everyday on SO. – sooprise Jul 09 '10 at 14:19
  • @Tim: Btw, the C# equivalent of VB's `Or` (non-short-circuiting) would by a single `|`. – Lucas Jul 09 '10 at 14:20
  • @Tim Coker: is there a short circuiting equivalent of `and` in VB? For instance in C# `if (array != null && array.length > 0)` is safe. – JeremyP Jul 09 '10 at 14:43
  • @Lucas, that's even more interesting, Thanks for sharing these tips everyone! – sooprise Jul 09 '10 at 18:15
  • 3
    Jon Skeet has spoken! – RedAces Jan 22 '14 at 15:59
  • if (array?.Length == 0) – amit jha Dec 20 '17 at 13:55
  • 1
    @amit: No, you'd want to use ?? there as well: `array?.Length ?? 0 == 0` – Jon Skeet Dec 20 '17 at 13:56
  • is there something wrong in the condition that i have written? Its working properly for me. i am doing unit test and its not breaking – amit jha Dec 20 '17 at 14:19
  • 1
    @amitjha: It's not equivalent to the condition in my question. If `array` is null, then your `if` condition won't be met because `null` isn't equal to 0, whereas mine will. – Jon Skeet Dec 20 '17 at 14:22
  • i still think both are same. pardon me, if i am not able to understand. i am getting the desired result in unit test – amit jha Dec 20 '17 at 14:24
  • 2
    @amitjha: Well I don't know what your unit test looks like, but they're *not* the same. (Actually you need brackets round `array?.Length ?? 0` due to precedence, but...) See https://dotnetfiddle.net/uRM74Y – Jon Skeet Dec 20 '17 at 14:28
  • @JonSkeet is there a way to check an empty array like an empty List ? An array of integers after Clear call gets zeros in all indexes, but it is actually void of values. Something like Count is zero ? – kuldeep Oct 11 '19 at 09:25
  • 1
    @kuldeep: No, because that's not an empty array - that's an array with zeroes in. The length of an array doesn't change after construction, ever. That's a fundamental difference between arrays and `List`. – Jon Skeet Oct 11 '19 at 11:18
14

Yeah, for safety I would probably do:

if(array == null || array.Length == 0)
kemiller2002
  • 107,653
  • 27
  • 187
  • 244
11

You can use

if (array == null || array.Length == 0)

OR

if (!(array != null && array.Length != 0))

NOTE!!!!! To insure that c# will implement the short circuit correctly; you have to compare that the object with NULL before you go to the children compare of the object.

C# 7.0 and above

if(!(array?.Length != 0))
Waleed A.K.
  • 1,372
  • 11
  • 13
  • 1
    the expression must change to if( ! (array?.Length > 0 ) ) since without the parenthesis, the not operator tries to evaluate on the expression array?.length which is of int type and complains. and the check should be for length > 0 when using the not operator. – supi Aug 29 '20 at 05:04
  • `if( !(array?.Length > 0 ) )` works better thanks – Swaleh Matongwa Jan 28 '21 at 19:47
4

You can use .Length == 0 if the length is empty and the array exists, but are you sure it's not null?

Brian R. Bondy
  • 314,085
  • 114
  • 576
  • 619
2

This is the best way. Please note Array is an object in NET so you need to check for null before.

Arseny
  • 6,961
  • 4
  • 35
  • 52
2

As other have already suggested it is likely you are getting a NullReferenceException which can be avoided by first checking to see if the reference is null. However, you need to ask yourself whether that check is actually warranted. Would you be doing it because the reference really might be null and it being null has a special meaning in your code? Or would you be doing it to cover up a bug? The nature of the question leads me to believe it would be the latter. In which case you really need to examine the code in depth and figure out why that reference did not get initialized properly in the first place.

Brian Gideon
  • 45,093
  • 12
  • 98
  • 145
2

Jon Skeet answered correctly. Just remember that the order of the test in the "IF" is important. Check for the null before the length. I also prefer to put the null on the left side of the equal which is a habit I got from Java that made the code more efficient and fast… I don't think it's important in a lot of application today, but it's a good practice!

if (null == array || array.Length == 0)
Community
  • 1
  • 1
Sylvain Perron
  • 403
  • 3
  • 7
2

If array is null, trying to derefrence array.Length will throw a NullReferenceException. If your code considers null to be an invalid value for array, you should reject it and blame the caller. One such pattern is to throw ArgumentNullException:

void MyMethod(string[] array)
{
    if (array == null) throw new ArgumentNullException(nameof(array));

    if (array.Length > 0)
    {
        // Do something with array…
    }
}

If you want to accept a null array as an indication to not do something or as an optional parameter, you may simply not access it if it is null:

void MyMethod(string[] array)
{
    if (array != null)
    {
        // Do something with array here…
    }
}

If you want to avoid touching array when it is either null or has zero length, then you can check for both at the same time with C#-6’s null coalescing operator.

void MyMethod(string[] array)
{
    if (array?.Length > 0)
    {
        // Do something with array…
    }
}

Superfluous Length Check

It seems strange that you are treating the empty array as a special case. In many cases, if you, e.g., would just loop over the array anyway, there’s no need to treat the empty array as a special case. foreach (var elem in array) {«body»} will simply never execute «body» when array.Length is 0. If you are treating array == null || array.Length == 0 specially to, e.g., improve performance, you might consider leaving a comment for posterity. Otherwise, the check for Length == 0 appears superfluous.

Superfluous code makes understanding a program harder because people reading the code likely assume that each line is necessary to solve some problem or achieve correctness. If you include unnecessary code, the readers are going to spend forever trying to figure out why that line is or was necessary before deleting it ;-).

binki
  • 6,057
  • 3
  • 49
  • 84
1

Your suggested test is fine, so long as the array is intialised...

Martin.

Martin Milan
  • 6,170
  • 2
  • 30
  • 43
1

check if the array is null first so you would avoid a null pointer exception

logic in any language: if array is null or is empty :do ....

Saher Ahwal
  • 8,230
  • 28
  • 75
  • 136
1

Since .Net >= 5.0 the best way is to use Any:

if(!array.Any()) {
   //now you sure it's empty
}

For nullable arrays:

if(!(array?.Any() == true)) {
   //now you sure it's null or empty
}
poletaew
  • 145
  • 10
0

do you mean empty or null, two different things,

if the array is instantiated but empty, then length is correct, if it has not been instantiated then test vs null

Pharabus
  • 6,003
  • 1
  • 24
  • 39
0

// there is another method to check if the array contains items or not

if ( array.Count == 0) return;
  • Welcome to Stack Overflow, thanks for your first answer! Unfortunately I believe your answer has the same problem as the original question, which is that if the array is null it will cause a Null Reference Exception – Kevin Apr 06 '21 at 22:20