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?
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.
Yeah, for safety I would probably do:
if(array == null || array.Length == 0)
You can use .Length
== 0 if the length is empty and the array exists, but are you sure it's not null?
This is the best way. Please note Array is an object in NET so you need to check for null before.
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
Your suggested test is fine, so long as the array is intialised...
Martin.
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.
Jon Skeet answered correctly. Just remeber that the order of the test in the "IF" is important. Check for the null before the lenght. I also prefer to put the null on the left side of the equal...just 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 good practice.
if(null == array || array.Length == 0)
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.
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 ....