Is there a nice simple & elegant way to make ICollection more fluent in C#?
c#, fluent, icollection, method-chaining
Solution
While fluent is nice, I'd be more interested in adding an `AddRange` (or two):
public static void AddRange<T>(this ICollection<T> collection,
params T[] items)
{
if(collection == null) throw new ArgumentNullException("collection");
if(items == null) throw new ArgumentNullException("items");
for(int i = 0 ; i < items.Length; i++) {
collection.Add(items[i]);
}
}
public static void AddRange<T>(this ICollection<T> collection,
IEnumerable<T> items)
{
if (collection == null) throw new ArgumentNullException("collection");
if (items == null) throw new ArgumentNullException("items");
foreach(T item in items) {
collection.Add(item);
}
}
The `params T[]` approach allows `AddRange(1,2,3,4,5)` etc, and the `IEnumerable<T>` allows use with things like LINQ queries.
If you want to use a fluent API, you can also write `Append` as an extension method in C# 3.0 that preserves the original list type, by appropriate use of generic constraints:
public static TList Append<TList, TValue>(
this TList list, TValue item) where TList : ICollection<TValue>
{
if(list == null) throw new ArgumentNullException("list");
list.Add(item);
return list;
}
...
List<int> list = new List<int>().Append(1).Append(2).Append(3);
(note it returns `List<int>`)
Problem
Example: I would like to have the `Add` method of `ICollection` of a custom collection class to implement method chaining and fluent languages so I can do this: ``` randomObject.Add("I").Add("Can").Add("Chain").Add("This"). ``` I can think of a few options but they are messy and involves wrapping ICollection in another interface and so forth.