Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
zlatanov opened this issue Dec 8, 2019 · 3 comments · Fixed by #675
Closed

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

zlatanov opened this issue Dec 8, 2019 · 3 comments · Fixed by #675

Comments

@zlatanov
Copy link
Contributor

zlatanov commented Dec 8, 2019

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?

@Dotnet-GitSync-Bot Dotnet-GitSync-Bot added area-System.Reflection untriaged New issue has not been triaged by the area owner labels Dec 8, 2019
@slang25
Copy link
Contributor

slang25 commented Dec 8, 2019

Relevant discussion: dotnet/coreclr#23774 (comment)

@jkotas
Copy link
Member

jkotas commented Dec 8, 2019

Submitted #674 to fix the annotations on the internal implementation details and add some comments.

@zlatanov
Copy link
Contributor Author

zlatanov commented Dec 8, 2019

Totally forgot about nullable value types and boxing. Now it makes sense.

@ahsonkhan ahsonkhan added this to the 5.0 milestone Dec 28, 2019
@ahsonkhan ahsonkhan removed the untriaged New issue has not been triaged by the area owner label Dec 28, 2019
@ghost ghost locked as resolved and limited conversation to collaborators Dec 11, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants