Dynamic casting

How to set a dynamic type to a generic type?

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); } 
+4
source share
2 answers

To do in "regular" C #, you must use reflection to get MethodInfo, then use MakeGenericMethod () and Invoke (). However, this is simpler:

 Foo((dynamic)testObj); 

Thinking Approach Here:

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

You cannot do this, because in the Foo function you have to do something with the collection, and there is no guarantee that the type will be safe.

The only way is to use the “object” and then apply the Fooo function to the correct type.

0
source

All Articles