Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a good way to clear an ICollection<T> without knowing T?

Tags:

c#

.net

generics

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?

like image 402
jnm2 Avatar asked Feb 16 '23 01:02

jnm2


1 Answers

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.

like image 156
Adam Houldsworth Avatar answered May 12 '23 06:05

Adam Houldsworth