Skip to content

Instantly share code, notes, and snippets.

@jagregory
Created February 14, 2012 10:27
Show Gist options
  • Select an option

  • Save jagregory/1825592 to your computer and use it in GitHub Desktop.

Select an option

Save jagregory/1825592 to your computer and use it in GitHub Desktop.
Ways of handling null collections and AddRange
// a)
if (items != null)
collection.AddRange(items)
// b)
collection.AddRange(items ?? new Foo[0])
@jagregory

Copy link
Copy Markdown
Author

@robashton I think that should be collection.NullSafeAddRange(items)?

@ashic

ashic commented Feb 14, 2012

Copy link
Copy Markdown

Just use Rob's extension method...nice and clean...and what I use on "real" projects ;)

@ashic

ashic commented Feb 14, 2012

Copy link
Copy Markdown

@jagregory collection.CheckIfThisIsNullAndIfThisIsNotAddTheItemsInTheCollectionToMe(items); [Something Neil might write ;) ]

@robashton

Copy link
Copy Markdown

@jagregory I don't like it, not enough job security

@leniel

leniel commented Mar 19, 2014

Copy link
Copy Markdown

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);
    }
}

@RodionOrets

Copy link
Copy Markdown

@leniel How do you call this extension method on self if self is null? It seems like it would cause some exception))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment