I have a list of collections of various item types.
The list is typed as List<IEnumerable>; because IEnumerable is the only non-generic interface from ICollection<T>, and I need to add e.g. ICollection<Contact> and ICollection<Partnership> collections in this list.
Later, in entity utility code, I need to clear the collections. The only solution I've found so far is:
collection.GetType().GetInterface("ICollection`1").InvokeMember("Clear",
        BindingFlags.Public | BindingFlags.Instance | BindingFlags.InvokeMethod,
        null,
        collection,
        new object[0]);
Is there anything more elegant I can use?
There aren't many options if you're constrained by ICollection<T> as your lowest type. A less-wordy implementation that involves the DLR is to use dynamic and duck-type it:
    static void Main(string[] args)
    {
        var listOfLists = new List<IEnumerable>();
        var names = new List<string>();
        var ages = new List<int>();
        listOfLists.Add(names);
        listOfLists.Add(ages);
        foreach (dynamic list in listOfLists)
        {
            list.Clear();
        }
    }
Or you can make assumptions about possibly implemented interfaces and test for one with Clear defined:
        foreach (var list in listOfLists)
        {
            if (list is IList)
            {
                (list as IList).Clear();
            }
        }
If you can get into the type hierachy, create your own interface that your collections use and define your own Clear.
This is mainly a problem because the pre-.NET 2.0 collections and interfaces do not mesh well with the .NET 2.0 collections and interfaces.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With