Search code examples
c#.netgenericsreflectionilist

Dynamically creating a new instance of IList's type


My application is processing IList's. ILists of different user defined types. I'm thinking that i can use reflection to to see what type of object the IList contains and then create a new instance of that type and subsequently add that to the IList itself?

So at any one time I might be processing

IList<Customer> l;

and I'd like to create a new instance of Customer

Customer c = new Customer(0, "None")

and then add that onto the list

l.Add(c);

Obviously doing this dynamically at run-time is the crux of the problem. Hope somebody can give me some pointers. Thanks brendan


Solution

  • Try this:

        public static void AddNewElement<T>(IList<T> l, int i, string s)
        {
            T obj = (T)Activator.CreateInstance(typeof(T), new object[] { i, s });
            l.Add(obj);
        }
    

    Usage:

        IList<Customer> l = new List<Customer>();
        l.Add(new Customer(1,"Hi there ..."));
    
        AddNewElement(l, 0, "None");
    

    (EDIT):

    Try this then:

        public static void AddNewElement2(IList l, int i, string s)
        {
            if (l == null || l.Count == 0)
                throw new ArgumentNullException();
            object obj = Activator.CreateInstance(l[0].GetType(), new object[] { i, s });
            l.Add(obj);
        }