IsNullOrEmpty equivalent for Array? C#

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.


You could create your own extension method:

public static bool IsNullOrEmpty<T>(this T[] array)
{
    return array == null || array.Length == 0;
}

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)) {

Tags:

C#

Arrays