73

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 a look in the Array class for a function such as this but couldn't see anything.

i.e.

var a = new string[]{};
string[] b = null;
var c = new string[]{"hello"};

IsNullOrEmpty(a); //returns true
IsNullOrEmpty(b); //returns true
IsNullOrEmpty(c); //returns false
10
  • 1
    What's wrong with if (arr != null && arr.Length != 0)? Or create an extension method if you need to use this repeatedly. Commented Dec 19, 2011 at 10:42
  • 6
    @CodyGray same thing that's wrong with it for strings, you don't want to do that all over the place. Commented Dec 19, 2011 at 10:43
  • @CodyGray - I agree, but I can see it becoming a pain to write if you had to write it repeatedly. I've got an extension method in most of my projects that does exactly this. Commented Dec 19, 2011 at 10:44
  • 1
    @CodyGray - The difference is that an extension method means typing 2 or 3 characters and then using IntelliSense to autocomplete. You have to write if (arr != null && arr.Length != 0) in its entirety. Commented Dec 19, 2011 at 10:47
  • 1
    @Yuriy: No, there's no special optimization going on there as far as I'm aware of. To begin with, the compiler does very little optimizing in C#. Almost all optimizations are handled by the JITer at run-time. Yes, it's quite likely that such a short method would be inlined by the JITer, but there's no guarantee. But even if that happened, there'd be no difference between the method call and the above code. There's nothing magic going on inside of the IsNullOrEmpty method—it's just there for convenience reasons. Early versions of the JITer actually had problems getting the optimization right. Commented Dec 19, 2011 at 11:01

10 Answers 10

81

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.


Update for 2025: These days you can use the null conditional operator and null coalescing operator to simplify the check inline, e.g. (array?.Length ?? 0) == 0 - the array?.Length part evaluates to the length of the array if it is not null, or null otherwise. The (...) ?? 0 part evaluates to the left hand expression if its value is not null, otherwise zero. By combining the two, you get the length of the array if it is not null, or zero if the array is null. The brackets are required due to operator precedence (?? has lower precedence than ==).

Naturally, you could still wrap this in an 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?.Length ?? 0) == 0;
}

For correct behaviour with very large arrays, one should use LongLength instead of Length.

Since it came up in the comments, it is important to note that calling an extension method on a null object is 100% valid and will not throw a NullReferenceException in the same way that calling an instance method on a null object would. This is because extension methods are implemented as static methods, so when you type array.IsNullOrEmpty() what you're really getting under the hood is MyExtensionMethods.IsNullOrEmpty(array), which operates in exactly the same way as the String.IsNullOrEmpty() static method.

Sign up to request clarification or add additional context in comments.

8 Comments

Given either of the variables (a,b or c) could you demonstrate it's usage? The only way I can see it working is new Array().IsNullOrEmpty(a);
No need for the parenthesis. Also you're overriding the normal behavior of what happens when you call a method on a null instance, so I'd put some xml comments for intellisense.
@YuriyFaktorovich - Yeah, the parenthesis are just a habit really. Feels wierd to me if I have combining logic without them. You're correct on the null behaviour, so I'll update.
If it really bothers you to call an extension method on a possibly null reference, you can also use the syntax ExtensionClass.IsNullOrEmpty(arr) (which is what the compiler is effectively doing), but that's not the normal way of using an extension method.
@Marc The reason that it doesn't throw is that extension methods are static and do not have the same contract as instance methods when it comes to null references. When you write var empty = a.IsNullOrEmpty(); what you're really using is syntactic sugar that gets turned into bool empty = MyArrayExtensions.IsNullOrEmpty(a); under the hood. This answer was written in 2011 so it came long before null conditional or null coalescing operators. These days you'd just do (array?.Length ?? 0) == 0 and do away with the need for an extension method.
|
47

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

Comments

39

You could create your own extension method:

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

5 Comments

@Polynomial which version of .net? Simply doing new int[0].IsNullOrEmpty<int>() throws an exception for me. But that works with yours. Now if you declare it any other way, it works fine.
@YuriyFaktorovich - Running .NET 4.0.30319 on Win7 x64, works fine regardless of whether I use <int> or let the compiler infer the type.
Never mind, now it works for some reason. I assume I made some mistake.
@YuriyFaktorovich - Probably a bit late on this comment, but I think you're missing brackets; i.e. (new int[0]).IsNullOrEmpty<int>();
Polynomial's answer results in a conflict with another existing extension method I use: error CS0121: The call is ambiguous between the following methods or properties: 'System.ExtensionMethods.IsNullOrEmpty(System.Array)' and 'System.Collections.Generic.ExtensionMethods.IsNullOrEmpty<T>(System.Collections.Generic.IEnumerable<T>)' - so I like this answer better.
10

More generic if you use ICollection<T>:

public static bool IsNullOrEmpty<T> (this ICollection<T> collection)
{
    return collection == null || collection.Count == 0;
}

Comments

6

This is an updated C# 8 version of the (currently) up-voted answer

public static bool IsNullOrEmpty<T>([NotNullWhen(false)] this T[]? array) =>
    array == null || array.Length == 0;

1 Comment

5
if (array?.Any() != true) { ... }
  • Don't forget having using System.Linq;
  • Note one must explicitly compare against true since the underlying type is bool?

Comments

3

In case you initialized you array like

string[] myEmpytArray = new string[4];

Then to check if your array elements are empty use

myEmpytArray .All(item => item == null)

Try

 public static bool IsNullOrEmpty<T> (this ICollection<T> collection)
 {
    if (collection == null || collection.Count == 0)
        return true;
    else
       return collection.All(item => item == null);
 }

Comments

2

You can also use Any on creating your extension method:

public static bool IsNullOrEmpty<T>(this T[] array) where T : class
    {
        return (array == null || !array.Any());
    }

Don't forget to add using System.Linq; on your using statements.

Comments

2

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"

Comments

0

Checking for null or empty or Length has been simplified with C# Linq. With null coalesce operator, one can simply do this:

if (array?.Any())
    return true;
else return false;

1 Comment

"Cannot implicitly convert 'bool?' to 'bool'"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.