-
-
Save jagregory/1825592 to your computer and use it in GitHub Desktop.
// a) | |
if (items != null) | |
collection.AddRange(items) | |
// b) | |
collection.AddRange(items ?? new Foo[0]) |
I know, I know, I know!!
public static class IEnumerableExtensions {
public static void AddTo<T>(this IEnumerable<T> self, ICollection<T> destination) {
if(self != null) destination.AddRange(self);
}
}
and
items.AddTo(collection);
What do I win?
what...nobody for good old
if(null != items) collection.AddRange(items);
?
@ashic Same difference there really, except yours is more verbose than both :)
I personally prefer B, mainly because it's got a bit less indentation and the AddRange
is a little more focal; that being said, having the new array is a bit of a shame. I could use Enumerable.Empty()
which will only allocate a new array the first time around, but that just isn't as neat and tidy.
@robashton I think that should be collection.NullSafeAddRange(items)
?
Just use Rob's extension method...nice and clean...and what I use on "real" projects ;)
@jagregory collection.CheckIfThisIsNullAndIfThisIsNotAddTheItemsInTheCollectionToMe(items); [Something Neil might write ;) ]
@jagregory I don't like it, not enough job security
Small correction to @robashton's extension because ICollection
doesn't have AddRange
:
using System.Collections.Generic;
public static class IEnumerableExtensions
{
public static void AddTo<T>(this IEnumerable<T> self, List<T> destination)
{
if(self != null) destination.AddRange(self);
}
}
@leniel How do you call this extension method on self
if self
is null
? It seems like it would cause some exception))
I agree with @flq.