If (Array.Length == 0)

后端 未结 12 2012
耶瑟儿~
耶瑟儿~ 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 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.

提交回复
热议问题