Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a nice simple & elegant way to make ICollection more fluent in C#?

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.

like image 799
danmine Avatar asked Nov 29 '22 19:11

danmine


2 Answers

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

like image 97
Marc Gravell Avatar answered Dec 15 '22 13:12

Marc Gravell


You could also use an extension method that would be usable with any ICollection<T> and save you from writing your own collection class:

public static ICollection<T> ChainAdd<T>(this ICollection<T> collection, T item)
{
  collection.Add(item);
  return collection;
}
like image 34
Curtis Buys Avatar answered Dec 15 '22 12:12

Curtis Buys