Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question on two different class extension patterns

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?

like image 486
IamIC Avatar asked Aug 06 '26 00:08

IamIC


1 Answers

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.

like image 131
Jon Skeet Avatar answered Aug 08 '26 17:08

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!