以下のように、nullチェック後にnullが渡された引数の名前を例外に渡したい場合がある。
public static void DoSomething(object thisCantBeNull)
{
if (thisCantBeNull == null)
throw new ArgumentException("thisCantBeNull");
}
このような場合、文字列を使用するのではなく、nameof
演算子を使ってローカル変数の名前を取得すべき。
public static void DoSomething(object thisCantBeNull)
{
if (thisCantBeNull == null)
throw new ArgumentException(nameof(thisCantBeNull));
}
一般に、関数名・変数名等の文字列を使用したメタプログラミングは、静的型付けによる型安全性やVisual Studio等のツールによるサポートを手放すことになるため、できるだけ避けるべき。