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?
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
You can use .Length
== 0 if the length is empty and the array exists, but are you sure it's not null?
Your suggested test is fine, so long as the array is intialised...
Martin.
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.
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.
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
}