Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If (Array.Length == 0)

Tags:

arrays

c#

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?

like image 866
sooprise Avatar asked Jul 09 '10 14:07

sooprise


People also ask

Does length of array include 0?

Arrays in Java use zero-based counting. This means that the first element in an array is at index zero. However, the Java array length does not start counting at zero.

Is array length is same as array length 0?

Is there any difference between checking an array's length as a truthy value vs checking that it's > 0? Since the value of arr. length can only be 0 or larger and since 0 is the only number that evaluates to false , there is no difference.

What is an array of length 0?

A zero length array is simply an array with nothing in it. It is an advantage to have such an array, especially in Java, so you can return a valid array and guarantee that your length check never fails. In Java, an array even of primitive types (i.e. int[] ) is still an object. It has a length property.

Is array length 0 Falsy?

If the length of the object is 0, then the array is considered to be empty and the function will return TRUE. Else the array is not empty and the function will return False.


2 Answers

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.

like image 169
Jon Skeet Avatar answered Sep 28 '22 03:09

Jon Skeet


Yeah, for safety I would probably do:

if(array == null || array.Length == 0) 
like image 26
kemiller2002 Avatar answered Sep 28 '22 05:09

kemiller2002