0

I'm working on some kind of scheduler, who gets the name of a class out of the DB and then executes a method of that class.

The problem is, that I can't get the reference to the class.

What I basically want:

    using MyNameSpace;
...
    Type myType = Type.GetType("MyNameSpace.MyClass");
    myInterface myObject = (myInterface)Activator.CreateInstance(myType);
    myObject.Run();

I know I need the assembly name so I tried something like this:

Type myType = typeof(object).Assembly.GetType("MyNameSpace.MyClass");

But the type is always null.

The wanted class lies in the same solution but in an other project. How can I get the referencee, so that I can execute the run() method?

thx

Jester
  • 56,577
  • 4
  • 81
  • 125
Dave
  • 263
  • 3
  • 12
  • 2
    What do you think `typeof(object).Assembly` does? It'll return `mscorlib`, not your referenced assembly. `mscorlib` does not contain your types. Use an Assembly Qualified Name, see [duplicate](http://stackoverflow.com/questions/3512319/resolve-type-from-class-name-in-a-different-assembly). – CodeCaster Mar 22 '16 at 17:14
  • The example in the "duplicate" is not working. It just works with System.String, but not with my own class: Type myType = Type.GetType("CSTurbo.AppWeb.Lib.Jobs.UpdateMetadataJob, AssemblyName"); – Dave Mar 22 '16 at 17:30
  • 1
    Then click one or two links further or try searching some more: [Type.GetType(“namespace.a.b.ClassName”) returns null](http://stackoverflow.com/questions/1825147/type-gettypenamespace-a-b-classname-returns-null), [Get type in referenced assembly by supplying class name as string?](http://stackoverflow.com/questions/11994057/get-type-in-referenced-assembly-by-supplying-class-name-as-string). Either the type is not in that assembly, or that assembly is not loaded. This question has been asked plenty of times before. – CodeCaster Mar 22 '16 at 17:33
  • Sorry for the duplicate. But I'm trying and searching for three hours now... – Dave Mar 22 '16 at 17:37
  • That's no problem, did either of my links solve the problem now? If not, please [edit] your question to show your project structure (which project contains which assemblies and namespaces) and how exactly you're calling `Type.GetType()` and I'll be happy to reopen. Basically this issue is: `Type.GetType()` works for the current assembly (usually the code the assembly is in) and `mscorlib` only, unless you specify the assembly name (preferably fully qualified). When it's then still not finding your type, the assembly is not loaded or doesn't contain that type. – CodeCaster Mar 22 '16 at 17:39

1 Answers1

0

try this Type myType = typeof(IMyInterface).Assembly.GetType("MyNameSpace.MyClass");

jalil
  • 85
  • 10