Search code examples
c#reflectionactivator

Need a type safe method of creating object


string attribute = doc.SelectSingleNode("/class/@name").Value.ToString();
ObjectHandle employee = Activator.CreateInstance("EmployeeData", attribute);
Object employeeObject = employee.Unwrap();
return employeeObject;

'EmployeeData' is the current executing assembly. Attribute is selected from entry node of an XML file. I need to create and return an object in a more type safe way, without using ObjectHandle and UnWrap(). Can anyone help?


Solution

  • It sounds like this would do the job:

    var type = Assembly.GetExecutingAssembly().GetType(attribute);
    return Activator.CreateInstance(type);
    

    Using the CreateInstance(Type) overload guarantees that the assembly defining the type is already loaded, so that overload is free to return a straight object.