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

Remove class constraint on AsNonNull() #5296

Merged
merged 1 commit into from
Jul 6, 2022

Conversation

smoogipoo
Copy link
Contributor

@smoogipoo smoogipoo commented Jul 6, 2022

This change is the only exact combination of things I can find that replicates the inspections provided by !.

My tests are:

#nullable enable
    object a = new object();
    object a1 = a!;
    object a2 = a.AsNonNull();
    Debug.Assert(a1 == null);
    Debug.Assert(a2 == null);

    object? b = new object();
    object b1 = b!;
    object b2 = b.AsNonNull();
    Debug.Assert(b1 == null);
    Debug.Assert(b2 == null);

    object? c = null;
    object c1 = c!;
    object c2 = c.AsNonNull();
    Debug.Assert(c1 == null);
    Debug.Assert(c2 == null);

    int d = 5;
    int d1 = d!;
    int d2 = d.AsNonNull();
    Debug.Assert(d1 == null);
    Debug.Assert(d2 == null);

    int? e = 5;
    int? e1 = e!;
    int? e2 = e.AsNonNull();
    Debug.Assert(e1 == null);
    Debug.Assert(e2 == null);

    int? f = null;
    int? f1 = f!;
    int? f2 = f.AsNonNull();
    Debug.Assert(f1 == null);
    Debug.Assert(f2 == null);
#nullable disable

Here's a comparison leading to my results. Open each image in a tab to see the differences.

Master: https://user-images.githubusercontent.com/1329837/177527783-e7616647-4a80-488c-8a04-83aa02c60919.png
Removing the T type: https://user-images.githubusercontent.com/1329837/177527683-a5b72f6e-21b3-4420-99c0-287c9bc5f456.png
Trying [return: NotNull]: https://user-images.githubusercontent.com/1329837/177528220-c924e752-ec75-43b5-80ab-caf94f4c775e.png
Using [return: NotNullIfNotNull("obj")]: https://user-images.githubusercontent.com/1329837/177528133-07c0629d-eba0-4e92-ba70-504c37e60948.png

{
return obj!;
}
[return: NotNullIfNotNull("obj")]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunate that the attribute requires literal string since nameof isn't supported on parameter names, there seem to be proposals about it as well (dotnet/csharplang#373 (comment)).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants