Short answer: You can't add items to IEnumerable<T>
Slightly longer explanation:
IEnumerable
is an interface that is solely concerned about being able to enumerate/iterate over the collection of items. This is the only purpose of an existence of IEnumerable
. It abstracts away any notion of the manner of storing or retrieving the enumerable items (it might be a string of characters, list of items, a stream of bytes or series of a computation results), thus if you have an interface that is an IEnumerable
, you can't add items to it, you can only iterate across the items it provides.
That said, the correct way to add items to IEnumerable
is to return new IEnumerable
with the new items appended to the contents of the original.
Also with Linq libraries you have an extension method that allows casting your IEnumerable to a List via IEnumerable.ToList()
and you can add items to a list. THis moght not be the proper way though.
With Linq libraries in your namespace you can do the following:
using System;
using System.Collections.Generic;
using System.Linq;
namespace EnumTester
{
class Program
{
static void Main(string[] args)
{
IEnumerable<string> enum = GetObjectEnumerable();
IEnumerable<string> concatenated = enum.Concat(new List<string> { "concatenated" });
List<string> stringList = concatenated.ToList();
}
}
}