If (Array.Length == 0)

后端 未结 12 1974
耶瑟儿~
耶瑟儿~ 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:53

    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.

    C# 7.0 and above

    if(!(array?.Length != 0))
    

提交回复
热议问题