-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Description
I am trying to use the new C# 8 nullability feature in our new projects and while trying to fix some warnings in regard to Activator.CreateInstance, I found out that it returns nullable object.
But after I looked at the code to see in which case does it really return null because I thought it wasn't possible, it turns out it doesn't. See code:
runtime/src/libraries/System.Private.CoreLib/src/System/Activator.RuntimeType.cs
Lines 82 to 94 in 4f9ae42
| public static object? CreateInstance(Type type, bool nonPublic) => | |
| CreateInstance(type, nonPublic, wrapExceptions: true); | |
| internal static object? CreateInstance(Type type, bool nonPublic, bool wrapExceptions) | |
| { | |
| if (type is null) | |
| throw new ArgumentNullException(nameof(type)); | |
| if (type.UnderlyingSystemType is RuntimeType rt) | |
| return rt.CreateInstanceDefaultCtor(publicOnly: !nonPublic, skipCheckThis: false, fillCache: true, wrapExceptions: wrapExceptions); | |
| throw new ArgumentException(SR.Arg_MustBeType, nameof(type)); | |
| } |
Here is the signature of CreateInstanceDefaultCtor:
runtime/src/coreclr/src/System.Private.CoreLib/src/System/RuntimeType.CoreCLR.cs
Line 3980 in 4f9ae42
| internal object CreateInstanceDefaultCtor(bool publicOnly, bool skipCheckThis, bool fillCache, bool wrapExceptions) |
Is this something that can be fixed and the annotation to be correct, or is there an obscure case in other runtimes and implementations where Activator.CreateInstance(Type) could possibly return null?