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.
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.