63

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
Cœur
  • 37,241
  • 25
  • 195
  • 267
maxp
  • 24,209
  • 39
  • 123
  • 201
  • 1
    What's wrong with `if (arr != null && arr.Length != 0)`? Or create an extension method if you need to use this repeatedly. – Cody Gray - on strike Dec 19 '11 at 10:42
  • 5
    @CodyGray same thing that's wrong with it for strings, you don't want to do that all over the place. – Yuriy Faktorovich Dec 19 '11 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. – Polynomial Dec 19 '11 at 10:44
  • @YuriyFaktorovich Really? Why not? I don't see how that's any more difficult than `String.IsNullOrEmpty()`... – Cody Gray - on strike Dec 19 '11 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. – Polynomial Dec 19 '11 at 10:47
  • Fascinating, making coding decisions based on IntelliSense. I guess that's not how I write code. Maybe I'm old school. Nothing wrong with your way either, though. – Cody Gray - on strike Dec 19 '11 at 10:51
  • @CodyGray I believe `String.IsNullOrEmpty` is optimized by the compiler to be faster than an `if`. – Yuriy Faktorovich Dec 19 '11 at 10:54
  • 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. – Cody Gray - on strike Dec 19 '11 at 11:01
  • @CodyGray right, I meant the JIT Compiler. So they took it out? – Yuriy Faktorovich Dec 19 '11 at 11:08
  • @Yuriy: It was never there. The "optimization" happening in early versions was a removal of the check for `null`. Since that obviously caused programs calling the method to crash with a `NullReferenceException`, yes they took that out. There's no way to optimize the code further than the two simple checks. The `&&` operator already performs short-circuiting, which is all the optimization you're going to get. If the method is inlined, you lose nothing. If not, it's going to be marginally slower (probably not relevant). But there's no way that writing the code explicitly could be any slower. – Cody Gray - on strike Dec 19 '11 at 11:56

11 Answers11

74

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.

Polynomial
  • 27,674
  • 12
  • 80
  • 107
  • 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); – maxp Dec 19 '11 at 10:54
  • 1
    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. – Yuriy Faktorovich Dec 19 '11 at 10:56
  • @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. – Polynomial Dec 19 '11 at 11:02
  • @maxp - It's an extension method. You call it directly on the object, like `a.IsNullOrEmpty()`. See: http://msdn.microsoft.com/en-us/library/bb383977.aspx – Polynomial Dec 19 '11 at 11:11
  • 2
    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. – Nick Sep 15 '14 at 20:21
41

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)) {
Slai
  • 22,144
  • 5
  • 45
  • 53
38

You could create your own extension method:

public static bool IsNullOrEmpty<T>(this T[] array)
{
    return array == null || array.Length == 0;
}
Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Lee
  • 142,018
  • 20
  • 234
  • 287
  • 7
    I actually like this answer better than mine :) – Polynomial Dec 19 '11 at 10:52
  • @Polynomial which version of .net? Simply doing `new int[0].IsNullOrEmpty()` throws an exception for me. But that works with yours. Now if you declare it any other way, it works fine. – Yuriy Faktorovich Dec 19 '11 at 11:11
  • @YuriyFaktorovich - Running .NET 4.0.30319 on Win7 x64, works fine regardless of whether I use `` or let the compiler infer the type. – Polynomial Dec 19 '11 at 11:14
  • Never mind, now it works for some reason. I assume I made some mistake. – Yuriy Faktorovich Dec 19 '11 at 11:16
  • @YuriyFaktorovich - Probably a bit late on this comment, but I think you're missing brackets; i.e. `(new int[0]).IsNullOrEmpty();` – JohnLBevan Sep 18 '12 at 09:09
  • 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(System.Collections.Generic.IEnumerable)'` - so I like this answer better. – Kim Homann Feb 20 '23 at 13:39
10

More generic if you use ICollection<T>:

public static bool IsNullOrEmpty<T> (this ICollection<T> collection)
{
    return collection == null || collection.Count == 0;
}
Danyal Aytekin
  • 4,106
  • 3
  • 36
  • 44
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;
pulvinius
  • 61
  • 1
  • 2
  • Info on NotNullWhen: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/nullable-analysis – Tony Rush Oct 28 '21 at 16:36
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);
 }
jabu.hlong
  • 2,194
  • 20
  • 21
3
if (array?.Any() != true) { ... }
  • Don't forget having using System.Linq;
  • Note one must explicitly compare against true since the underlying type is bool?
Shmil The Cat
  • 4,548
  • 2
  • 28
  • 37
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.

Willy David Jr
  • 8,604
  • 6
  • 46
  • 57
1

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.

Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142
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;
Gauravsa
  • 6,330
  • 2
  • 21
  • 30
0

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"

Teodor Tite
  • 1,855
  • 3
  • 24
  • 31