Domanda

Is this bad practice (the returning null part)?

public static ObservableCollection<TSource> ToObservableCollection<TSource>(
    this IEnumerable<TSource> source)
{
    if (source == null) return null;
    return new ObservableCollection<TSource>(source);
}
È stato utile?

Soluzione

You should throw an ArgumentNullExcception. Most of the .NET Framework extension methods do this. Alternatively, do nothing and let the ObservableCollection<T> constructor do it.

public static ObservableCollection<TSource> ToObservableCollection<TSource>(this     IEnumerable<TSource> source)
{
    if (source == null)
    {
        throw new ArgumentNullException("source");
    }

    return new ObservableCollection<TSource>(source);
}

Altri suggerimenti

I write mine to handle null parameters, so I advocate null checks. Extension methods are emitted differently in IL code. They emitted as a static method of a class thereby the parameters can be null.

UPDATE: either throw an exception or handle the null value appropriately is how I deal with null values in my extension methods.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top