Search code examples
c#dynamic-typing

Dynamic typing in C#


I know this does not work, however does anyone have a way of making it work?

object obj = new object();
MyType typObj = new MyType();
obj = typObj;
Type objType = typObj.GetType();
List<objType> list = new List<objType>();
list.add((objType) obj);

EDIT:

Here is the current code: http://github.com/vimae/Nisme/blob/4aa18943214a7fd4ec6585384d167b10f0f81029/Lala.API/XmlParser.cs

The method I'm attempting to streamline is SingleNodeCollection

As you can see, it currently uses so hacked together reflection methods.


Solution

  • It seems you're missing an obvious solution:

    object obj = new object();
    MyType typObj = new MyType();
    obj = typObj;
    List<MyType> list = new List<MyType>();
    list.Add((MyType) obj);
    

    If you really need the dynamic route, then you could do something like this:

    object obj = new object();
    MyType typObj = new MyType();
    obj = typObj;
    Type objType = typObj.GetType();
    
    Type listType = typeof(List<>);
    Type creatableList = listType.MakeGenericType(objType);
    
    object list = Activator.CreateInstance(creatableList);
    MethodInfo mi = creatableList.GetMethod("Add");
    mi.Invoke(list, new object[] {obj});