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
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 reasonNote 2: as a bonus, the statement is also "thread-safe"
You could create your own extension method:
public static bool IsNullOrEmpty<T>(this T[] array)
{
return array == null || array.Length == 0;
}
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.
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)) {
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.
More generic if you use ICollection<T>
:
public static bool IsNullOrEmpty<T> (this ICollection<T> collection)
{
return collection == null || collection.Count == 0;
}