If (Array.Length == 0)

后端 未结 12 1912
耶瑟儿~
耶瑟儿~ 2020-12-23 11:23

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?

相关标签:
12条回答
  • 2020-12-23 11:57

    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

    0 讨论(0)
  • 2020-12-23 12:04

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

    0 讨论(0)
  • Your suggested test is fine, so long as the array is intialised...

    Martin.

    0 讨论(0)
  • 2020-12-23 12:06

    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.

    0 讨论(0)
  • 2020-12-23 12:06

    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.

    0 讨论(0)
  • 2020-12-23 12:06

    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
    }
    
    0 讨论(0)
提交回复
热议问题