My question as title above. For example,
IEnumerable<T> items = new T[]{new T("msg")};
items.ToList().Add(new T("msg2"));
but after all it only has 1 item inside.
Can we have a method like items.Add(item)
?
like the List<T>
My question as title above. For example,
IEnumerable<T> items = new T[]{new T("msg")};
items.ToList().Add(new T("msg2"));
but after all it only has 1 item inside.
Can we have a method like items.Add(item)
?
like the List<T>
Have you considered using ICollection<T> or IList<T> interfaces instead, they exist for the very reason that you want to have an 'Add' method on an IEnumerable<T>. IEnumerable<T> is used to 'mark' a type as being ...well.. enumerable or just a sequence of items without necessarily making any guarantees of whether the real underlying object supports adding/removing of items. Also remember that these interfaces implements IEnumerable<T> so you get all the extensions methods that you get with IEnumerable<T> as well.
To add second message you need to -
Easyest way to do that is simply
Then you can return list as IEnumerable also because it implements IEnumerable interface
In .net Core, there is a method
Enumerable.Append
that does exactly that.The source code of the method is available on GitHub..... The implementation (more sophisticated than the suggestions in other answers) is worth a look :).
you can do this.
Others have already given great explanations regarding why you can not (and should not!) be able to add items to an
IEnumerable
. I will only add that if you are looking to continue coding to an interface that represents a collection and want an add method, you should code toICollection
orIList
. As an added bonanza, these interfaces implementIEnumerable
.