What is the semantic difference between the following two methods:
public static bool IsNullOrEmpty(this Array value)
{
return (value == null || value.Length == 0);
}
and
public static bool IsNullOrEmpty<T>(this T[] value)
{
return (value == null || value.Length == 0);
}
Is there an advantage to one over the other?
The first will work for any array, including rectangular arrays and ones with a non-zero lower bound. It will also work when the compile-time type of the array is just Array, which may happen very occasionally with fairly weakly-typed APIs.
In short, the first is more general, and should work anywhere that the second does.
(I'm assuming you don't want any "extra" features from this, such as extra constraints on T in the second form... you just want something which will find out whether an array reference is null or refers to an empty array.)
EDIT: For IEnumerable, you'd use:
public static bool IsNullOrEmpty(this IEnumerable value)
{
if (value == null)
{
return true;
}
var iterator = value.GetEnumerator();
try
{
return !iterator.MoveNext();
}
finally
{
// Non-generic IEnumerator doesn't extend IDisposable
IDisposable disposable = iterator as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
}
The disadvantage of this of course is that it can very easily have side-effects - for example, you could pass in a LINQ query which would end up talking to a database.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With