11
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[C#] null許容参照時代のTry-Parseパターン

Last updated at Posted at 2020-09-02

Question

以下のメソッドは、trueを返す場合はvalueに非nullの値を格納し、falseを返す場合はnullを格納する。

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

では、このメソッドは、null許容参照型の導入時にどう変化させなければならないか。

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

と書いてしまうと、呼び出し側で面倒なことになる。

if (TryGetValue("hoge", out string? value)
{
    // nullを許容しない引数のメソッドに渡す際、!演算子が必要になる
    DisallowNullMethod(value!);
}

Answer

NotNullWhen属性、あるいは、 MaybeNullWhen属性をout引数に付ける。

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

下の場合、引数の型がnullを許容しない型になるが、メソッド内ではout引数にnullを代入できる。

こう書いておくと、このメソッドがtrueを返したコンテキストに限り、valueの値をnull非許容としてあつかえる。

// メソッドを呼び出す際は、null許容型な必要がある
if (TryGetValue("hoge", out string? value)
{
    // ここではvalueをnull非許容として扱える
    DisallowNullMethod(value);
}

参考にした情報

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

11
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?