IsNullOrEmpty equivalent for Array? C#

后端 未结 11 1408
轻奢々
轻奢々 2020-12-08 18:42

Is there a function in the .NET library that will return true or false as to whether an array is null or empty? (Similar to string.IsNullOrEmpty).

I had

相关标签:
11条回答
  • 2020-12-08 19:09

    Since C# 6.0, the null-propagation operator may be used to express concise like this:

    if (array?.Count.Equals(0) ?? true)
    

    Note 1: ?? false is necessary, because of the following reason

    Note 2: as a bonus, the statement is also "thread-safe"

    0 讨论(0)
  • 2020-12-08 19:12

    You could create your own extension method:

    public static bool IsNullOrEmpty<T>(this T[] array)
    {
        return array == null || array.Length == 0;
    }
    
    0 讨论(0)
  • 2020-12-08 19:12

    No, but you can write it yourself as an extension method. Or a static method in your own library, if you don't like calling methods on a null type.

    0 讨论(0)
  • 2020-12-08 19:13

    With Null-conditional Operator introduced in VS 2015, the opposite IsNotNullOrEmpty can be:

    if (array?.Length > 0) {           // similar to if (array != null && array.Length > 0) {
    

    but the IsNullOrEmpty version looks a bit ugly because of the operator precedence:

    if (!(array?.Length > 0)) {
    
    0 讨论(0)
  • 2020-12-08 19:16

    There isn't an existing one, but you could use this extension method:

    /// <summary>Indicates whether the specified array is null or has a length of zero.</summary>
    /// <param name="array">The array to test.</param>
    /// <returns>true if the array parameter is null or has a length of zero; otherwise, false.</returns>
    public static bool IsNullOrEmpty(this Array array)
    {
        return (array == null || array.Length == 0);
    }
    

    Just place this in an extensions class somewhere and it'll extend Array to have an IsNullOrEmpty method.

    0 讨论(0)
  • 2020-12-08 19:18

    More generic if you use ICollection<T>:

    public static bool IsNullOrEmpty<T> (this ICollection<T> collection)
    {
        return collection == null || collection.Count == 0;
    }
    
    0 讨论(0)
提交回复
热议问题