Adamsk1
Adamsk1

Reputation: 67

Use the "new" keyword to create an object using reflection

I'm completely new to reflection and I'm trying to call a class name from a db record and then load the class and run it but I'm pulling my hair out on where I'm going wrong, its probably something really silly I'm missing.

As an example I have my class in a different project and scripts folder, then call the name of it from the db record.

className = String.Format("Utilities.Scripts.{0}", script.ScriptClass);

Then in my main program I have

// Get a type from the string 
Type type = Type.GetType(className);

// Create an instance of that type
Object obj = Activator.CreateInstance(type);

// Retrieve the method you are looking for
MethodInfo methodInfo = type.GetMethod("start");

// Invoke the method on the instance we created above
methodInfo.Invoke(obj, null);

But I am getting the error as when debugging I can see my details passed into the GetType(className) but nothing goes through to the type and as such into the obj where it is erroring.

Upvotes: 3

Views: 1807

Answers (2)

James Curtis
James Curtis

Reputation: 794

You need to supply the Assembly Qualified Name of the type (as mentioned here) since the class is in a different project. Also, make sure that the assembly you are trying to load the type from is either in the same folder as the assembly trying to load it, or in the GAC.

For a class defined as below:

namespace Foo.Bar
{
    public class Class1
    {

    }
}

The full class name is Foo.Bar.Class1. The assembly qualified name also specifies the full name of the assembly, as in Foo.Bar.Class1, Foo.Bar, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35. You can find the Assembly Qualified Name of your type with somthing like:

Console.WriteLine(typeof(Foo.Bar.Class1).AssemblyQualifiedName)

Upvotes: 3

Jamiec
Jamiec

Reputation: 136104

The problem is in this line:

Type type = Type.GetType(className);

In that this particular overload of the method will not throw an exception when the type cannot be resolved. Instead use this overload which takes 2 booleans, one of which being throwOnError. Pass true for this parameter and you will get an exception which should help you debug why your type cannnot be resolved from the string you pass in.

I suspect you need a class name and assembly name

Utilities.Scripts.SomeClass, SomeAssemblyName

Upvotes: 0

Related Questions