Sako73
Sako73

Reputation: 10137

Reflection.Assembly.CreateInstance(string)

In .NET 4.0, if I have the following code:

....
T instantiatedClass;
try
{
    instantiatedClass = (T)assembly.CreateInstance(classFullName);
}
catch (Exception ex)
{
    errMsg = string.Format("Error creating an instance of type \"{0}\".", classes.First().FullName);
    throw new ApplicationException(errMsg, ex);
}

Assuming that classFullName is a correct type in the assembly, and that the type "T" implements a public interface, is there any circumstance where 1) No exception would be thrown, and 2) instantiatedClass would be null?

Thanks for any help.

Upvotes: 1

Views: 403

Answers (2)

Phil Wright
Phil Wright

Reputation: 22936

Based on your assumptions and if your type T is always an interface then a direct cast to T will throw an exception if the interface in question is not implemented by the created instance or if the type does not have a default constructor that can be called.

A better approach that avoids throwing an exception would be...

T interfaceVar = assembly.CreateInstance(classFullName) as T;
if (interfaceVar == null)
{
    // oops, does not implement interface T
}
else
{
    // yippee, it does implement interface T
}

You could use reflection on the target assembly to check if the required type exists, if it has a default constructor and if it implements the interface you are interested in. In that case you would avoid creating an instance at all, if all you want to know is if it has the specified interface.

Upvotes: 4

Gaute Løken
Gaute Løken

Reputation: 7912

If there is no default constructor or the assumption that classFullName is valid in the assembly is incorrect or anything prevents the CreateInstance call from calling a constructor an exception is thrown.

So the only way that this could fail for you is if the called constructor returns a null value. But this can't happen since if no exception is raised during construction, then the constructor call will return a reference to the new object, and if an exception is raised you catch it.

Upvotes: 1

Related Questions