How to add a item to a null IEnumerable<T>? RRS feed

  • Question

  • User-424843316 posted

    How to add a item to a null IEnumerable<T>?

    IEnumerable<T> a = null;

    IEnumerable<T> item = new T[] { ... };


    Sunday, June 14, 2015 10:43 PM


  • User-1910946339 posted

    IEnumerable is the wrong data type choice if you want to add elements.  The purpose of IEnumerable is to be able to traverse or enumerate in a forward manner a collection of elements.

    IList<T> would be a better choice if you wish to manipulate the collection.

    But you won't be able to add elements to something that is null.  Null means that the collection does not exist.  If it doesn't exist you can't add to it.

    You probably want something like

    IList<T> a = new List<T>();
    IList<T> items = new T[]{...};
    a = a.Concat(items);

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, June 14, 2015 11:16 PM