コードインスペクション: 「null」チェックを代入と結合する
このインスペクションは、C# 7.0 で導入された新しい構文である throw 式をサポートします。 スロー式を使用すると、別の式の途中で例外をスローできるため、スローを null チェックなどの他のタスクと組み合わせることができるようになりました。 これは、引数の値を変数に割り当てる前に引数の null をチェックする一般的な操作で、よりコンパクトな外観にすることができることを意味します。
以下の例では、ReSharper は null 合体演算子を使って、代入、null チェック、および例外スローを単一のステートメントにまとめています。
public class MyClass
{
private string myVariable;
public void SetValue(string newValue)
{
if (newValue == null)
{
throw new ArgumentNullException(nameof(newValue));
}
myVariable = newValue;
}
}
public class MyClass
{
private string myVariable;
public void SetValue(string newValue)
{
myVariable = newValue ?? throw new ArgumentNullException(nameof(newValue));
}
}
2026 年 6 月 12 日