kolian
kolian

Reputation: 43

Casting to a collection with a dynamic type

How can I set generic type dynamically?

 public class A
    {
        public int X { get; set; }

        public A()
        {
            X = 9000;
        }
    }

    public class Class1
    {

        public void Test()
        {
            List<A> theList = new List<A>() {
                new A { X = 1 },
                new A { X = 2 }               
            };


            object testObj = theList;
            var argType = testObj.GetType().GetGenericArguments()[0];


            Foo(testObj as ICollection<argType>); // ?                                           

        }

        public void Foo<T>(ICollection<T> items) where T:new()
        {
            T newItem = new T();    
            items.Add(newItem);    

        }

Upvotes: 4

Views: 895

Answers (2)

Mario Vernari
Mario Vernari

Reputation: 7304

You can't do that, because in the Foo function you are supposed to do something with the collection, and there's no guarantee that the type will be safe.

The only way is using an "object" then casting to the proper type within the Fooo function.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062502

To do in "regular" c# you would use reflection to obtain the MethodInfo, then use MakeGenericMethod() and Invoke(). However, this is easier:

Foo((dynamic)testObj);

The reflection approach here is:

var method = typeof(Class1).GetMethod("Foo").MakeGenericMethod(argType);
method.Invoke(this, new object[] { testObj });

Upvotes: 3

Related Questions