Generic Activator.CreateInstance(typeof(T), msg) marked as nullable

408 Views Asked by At

I have this generic method for throwing different exceptions with a different T depending on the context:

    private static T ThrowException<T>(string message) where T : Exception, new()
    {
        T? exception = Activator.CreateInstance(typeof(T), message) as T;          
        throw exception;
    }

The Activator.CreateInstance() returns a Nullable<T> instead of T, therefore I get a possible null warning on var exception.

I can't think of a situation where the var exception could possibly end up being null. It seems like the T : Exception constraint is not considered by the compiler, because all the T I can possibly pass must extend Exception, otherwise, I'll see an error given the constraint.

Even though I could solve the warning by doing an extra null check and returning a generic throw Exception if exception == null, I'd rather much prefer to do so only if this is really going to be a possible situation. If not, I'd rather just suppress the warning with a null forgiving operator (!).

Is there any scenario where exception can be null? If not, does it make logical sense to fix the warning instead of suppressing it (which seems to be a bad practice)?

Thanks in advance

1

There are 1 best solutions below

4
Mihinator3000 On

As it's stated in this pull request, CreateInstance method returns null only when called for Nullable<T> types, so in your case exception can never be null.

And btw you should probably use (T) cast instead of as T since you already know that returned value is T.