Search code examples
c#activator

Calling a class file name from a string containing the class name


I have a string that I'm getting from a database that contains a class name, for example: "w_task1". When I fetch the script name from the database, I don't know which script it is so can't write w_task1 t = new w_task1().

Instead I want it to be along the lines of (value of class name) t = new (value of class name)().

Class names I'm trying to open vary from: w_task1.cs - w_task25.

I've tried using the whole:

Type type = Type.GetType("w_task1");
object o = Activator.CreateInstance(type);

...But type is equal to null when the program's ran.

So how do I open the class from the string, without knowing the class type?


Solution

  • Your answer is here: get assembly by class name

    this question as been answered by Marc Gravell

    You have to find loaded assembly by your class name (linq will help) then do the reflexion stuff to call your method.

    I marked your question as duplicated.

    You cannot open a class by the file name. How your CLR can make the link between the file name and the Class inside?