views:

27

answers:

1

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?

+1  A: 

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.

Rewinder
Thanks for the hint. My questions was more about if type has to be string? Is there some build in stuff from the framework that get's the type as "Type" without doing anything?
gsharp