weaverbeaver
weaverbeaver

Reputation: 161

Activator.CreateInstance returns null

I have this small piece of code:

public static I CreateInstance<I>(string myClassName) where I : class
{
    Debug.Log("Instance: " + (Activator.CreateInstance(null, myClassName) as I));
    return Activator.CreateInstance(null, myClassName) as I;
}

void Test(string testName)
{
    testName = "TestProvider";
    var data = CreateInstance<IProviderInitializer>(testName).GetProviderInfo();
    Debug.Log("Data: " + data);
}

And the problem is that I get NULL Reference Exception and I have no idea why.

Upvotes: 0

Views: 6889

Answers (3)

AyCe
AyCe

Reputation: 756

Never use x as T when you expect x to be T. Always use (T) x instead in that case. That way you can detect mistakes where you happen to have the wrong type for an object early, instead of hiding them behind NullReferenceExceptions.

Upvotes: 5

D Stanley
D Stanley

Reputation: 152556

Rather than using the overload that takes the type as a string (and returns a handle to an object), you could create a Type object and pass that to the overload of CreateInstance that accepts a Type:

Type t = Type.GetType(myClassName);
return Activator.CreateInstance(t) as I;

Upvotes: 3

LeY
LeY

Reputation: 787

From the Documentation

public static System.Runtime.Remoting.ObjectHandle CreateInstance (string assemblyName, string typeName);

The CreateInstance method call return "ObjectHandle" type which is not convertable to "I", Activator.CreateInstance(null, myClassName) as I will always return null.

You need unwarp your object

public static void Main()
   {
      ObjectHandle handle = Activator.CreateInstance("PersonInfo", "Person");
      Person p = (Person) handle.Unwrap();
      p.Name = "Samuel";
      Console.WriteLine(p);
   }

Upvotes: 2

Related Questions