Reputation: 55499
I'm trying to troubleshoot a NullReferenceException
that's occuring on a production system. If the line number in the stack trace can be trusted, then it would seem to indicate that AppDomain.CreateInstanceAndUnwrap
returned null:
this.jobRunner =
(JobRunner)this.appDomain.CreateInstanceAndUnwrap(assemblyName, typeName);
// ...
try
{
this.jobRunner.Run(this.job); // <== NullReferenceException occurs here
}
However, MSDN Library doesn't specifically say that null is a possible return value:
Return Value
Type: System.Object
An instance of the object specified by typeName.
My question: Can AppDomain.CreateInstanceAndUnwrap
legitimately return null? If so, what would that mean?
Upvotes: 2
Views: 591
Reputation: 8084
Yes, AppDomain.CreateInstanceAndUnwrap
can legitimately return null.
Here is the reflected code for the method (using .NET Reflector):
[SecuritySafeCritical]
public object CreateInstanceAndUnwrap(string assemblyName, string typeName)
{
ObjectHandle handle = this.CreateInstance(assemblyName, typeName);
if (handle == null)
{
return null;
}
return handle.Unwrap();
}
Deeper we get:
[SecuritySafeCritical]
public ObjectHandle CreateInstance(string assemblyName, string typeName)
{
if (this == null)
{
throw new NullReferenceException();
}
if (assemblyName == null)
{
throw new ArgumentNullException("assemblyName");
}
return Activator.CreateInstance(assemblyName, typeName);
}
So the real question is: can Activator.CreateInstance
legitimately return null. And the answer is YES, it can return null on certain conditions. One example I've found is creating nullable types (see this SO question), but I'm sure there are other examples.
Upvotes: 3