Is it possible to instantiate an object based on a string value indicating its type?

I am trying to dynamically create an object of a specific type in a LINQ-to-XML query based on the string in my XML document. I'm used to being able to dynamically create an object of any type in PHP and JavaScript, just being able to write something like:

$obj = new $typeName();

Ideally, I would like to do something like:

List<someObj> = (from someObjs in XMLfile
                 select new someObj()
                 {
                     Name = (string)someObjs.Element("name"),
                     NestedObj = new someObjs.Element("nestedObj").Element("type")()
                     {
                         NestedName = (string)someObjs.Element("nestedObj").Element("name")
                     }
                 }).ToList();

I just can't figure out how to do this without grabbing the current executable assembly.

+3
source share
2 answers

You can use:

Activator.CreateInstance(Type.GetType(typeName))

Of course, this only works for types without a constructor without parameters.


Refresh (initialize the object):

# 4 :

dynamic newObj = Activator.CreateInstance(Type.GetType(typeName));
newObj.NestedName = str;

LINQ to XML :

var list = XMLFile.Select(someObjs => {
    dynamic nestedObj = Activator.CreateInstance(
       Type.GetType(someObjs.Element("nestedObj").Element("type")));
    nestedObj.NestedName = (string)someObjs.Element("nestedObj").Element("name");
    return new someObj {
        Name = (string)someObjs.Element("name"),
        NestedObj = nestedObj
    };
}).ToList();
+9

createinstance

+3

All Articles