Skip to content

Why Activator.CreateInstance(Type) returns nullable object? #674

@zlatanov

Description

@zlatanov

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:

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:

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?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions