IamIC
IamIC

Reputation: 18239

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?

Upvotes: 3

Views: 79

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1500495

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.

Upvotes: 4

Rikon
Rikon

Reputation: 2696

With going generic you could add a conditional that further restricts what T can be...

So you could restrict it with "where T : class" or "where T : ISomeInterface" (most notably you could do "where T : IDisposable" and ensure that your extension can't use anything that can't dispose

Upvotes: 2

Colin Desmond
Colin Desmond

Reputation: 4854

The second one uses generics hence is type safe.

Upvotes: 1

Related Questions