Skip to content

Possible Nullability Analysis Issue with TryPickTx Not Triggering Warnings #198

Description

@AntoninLolivier

I encountered an issue where the C# compiler does not issue a nullability warning when accessing a variable assigned via TryPickT1(out T1, out T0), even though it should be null when TryPickT1 returns false.

I checked the source code of OneOf, and I did not find any [MaybeNullWhen(false)] or similar annotations on the TryPickTx methods. The lack of such annotations might be the reason why the compiler does not properly track nullability in this case.

However, I am not sure if this is something that should be addressed within this repository, or if it is an intrinsic behavior of the C# compiler itself.


Steps to Reproduce

Code Example

class Program
{

    private class MyClass
    {
        public string Name { get; set; }
    }

    private static void Main()
    {
        OneOf<MyClass, string> result = TestNullability();

        if (result.TryPickT0(out MyClass? myClass, out string? @string)) return;

        string name = myClass.Name;
    }

    private static OneOf<MyClass, string> TestNullability() => "test";
}

Expected Behavior

The compiler should issue a nullable warning when accessing MyClass.Name, since myClass is null when TryPickT0 returns false.

Actual Behavior

No warning is issued, and the code compiles without any nullability concerns. And a NullReferenceException is thrown.


Additional Notes

  • I looked into the OneOf source code and did not find any [MaybeNullWhen(false)] annotation on TryPickTx.
  • This might be causing the issue, but I am unsure if this is something that should be fixed within OneOf, or if it is a behavior inherently tied to the C# compiler's nullability analysis.

Let me know if this is relevant to the repo, or if I should report it elsewhere. Thanks! 😊

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions