[C #] Try-Parse pattern in the nullable reference era

less than 1 minute read

Question

The following method stores a non-null value in value if it returns true, and stores null if it returns false.

bool TryGetValue(string key, out string value) { ... }

So how should this method change when introducing nullable reference types?

bool TryGetValue(string key, out string? value) { ... }

If you write, it will be troublesome on the caller side.

if (TryGetValue("hoge", out string? value)
{
    //When passing nulls to non-nullable argument methods!Operator required
    DisallowNullMethod(value!);
}

Answer

Add the NotNullWhen attribute or the MaybeNullWhen attribute to the out argument.

bool TryGetValue(string key, [NotNullWhen(true)] out string? value) { ... }
bool TryGetValue(string key, [MaybeNullWhen(false)] out string value) { ... }

In the case below, the argument type is a type that does not allow null, but null can be assigned to the out argument in the method.

If you write this, you can treat the value of value as nullable only in the context where this method returns true.

//Must be nullable when calling the method
if (TryGetValue("hoge", out string? value)
{
    //Here you can treat value as nullable
    DisallowNullMethod(value);
}

Referenced information

https://stackoverflow.com/questions/55526064/trygetvalue-pattern-with-c-sharp-8-nullable-reference-types
https://www.misuzilla.org/Blog/2019/09/25/NullableReferenceTypes