Search code examples
c#arrayslistarraylistgeneric-collections

c# create instance and add elements to a collection given a type, which can be: Arrays, Lists, Dictionaries, Queues, Stacks


I have the following code

public void example(Type t)
{
    var collector = (ICollection)Activator.CreateInstance(t);

    Debug.Log(collector);
}

this prints

System.Collections.Generic.List`1[System.Int32]
System.Collections.ArrayList

but I need to add elements


Explaining myself better

I have the type of ICollection, I need to take it to a generic structure that allows me to add or insert elements

public void example(Type t){

   var my_collector = new AnyClass((ICollection)Activator.CreateInstance(t));

   collector.Add(new element());
   //or
   collector.insert(new element(),0);
}

but, I'm not interested in printing the elements, this I did to show the types of collectors that will come. I'm only interested in adding or inserting elements in the new ICollector

Anyway, thanks for your answers


Solution

  • You can't add elements to an ICollection. You'll need to downcast 'collector' to IList, Queue, or Stack:

    switch (collector)
    {
        case IList list:
            list.Add("something");
            break;
        case Queue queue:
            queue.Enqueue("something");
            break;
        case Stack stack:
            stack.Push("something");
            break;
    }