Question

I've a section like this

<mySection type="Namespace.MyClass, AssemblyName" />

in my code I need to create an Instance of MyClass, so what I do is something like that:

string type = GetMySectionType(); // "Namespace.MyClass, AssemblyName"

var typeParts = type.Split(',');
var className = typeParts[0].Trim();
var assemblyName = typeParts[1].Trim();
var assembly = Assembly.Load(assemblyName);
var myObj = (MyClass)assembly.CreateInstance(className);

Im sure there is better way to do that, without string splitting, but i didn't find anything about it in google.

Edit: Is there some build in stuff from the framework that get's the type as "Type" without doing anything?

Was it helpful?

Solution

You could use the GetType(string typename) method. For example like this:

string type = GetMySectionType(); // "Namespace.MyClass, AssemblyName"
Type myType = Type.GetType(type);
var myObj = (MyClass)Activator.CreateInstance(myType);

see this page for more info.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top