8
29

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 1 year has passed since last update.

【C#】nameofって何?

Last updated at Posted at 2022-02-26

個人の備忘録です。

結論

  • nameof演算子に変数名、型、メンバー、メソッド名などの識別子を与えると、同等の文字列を得られる
  • 文字列を指定する場面でnameofを使うことで、コードの修正漏れを防ぎ保守性の高いコードにすることができる
  • nameof演算子はコンパイル時に評価され、実行時には影響を与えない
Console.WriteLine(nameof(System.Collections.Generic));  // output: Generic
Console.WriteLine(nameof(List<int>));  // output: List
Console.WriteLine(nameof(List<int>.Count));  // output: Count
Console.WriteLine(nameof(List<int>.Add));  // output: Add

var numbers = new List<int> { 1, 2, 3 };
Console.WriteLine(nameof(numbers));  // output: numbers
Console.WriteLine(nameof(numbers.Count));  // output: Count
Console.WriteLine(nameof(numbers.Add));  // output: Add

メリット

  • メンバなどが変更された際に、コンパイルエラーを表示してくれるため、コードの修正漏れを防ぎ保守性の高いコードにすることできる。
    • 文字列リテラルはコンパイラによって検証されない
    • nameofは式なので指定した変数名やメソッド名が正しいかどうかコンパイル時にチェックされる
switch (property.Name)
{
    case nameof(Model.Field1):  // 修正などされて一致しなくなればエラーが出る
    case nameof(Model.Field2):  // 修正などされて一致しなくなればエラーが出る
        Console.WriteLine("hoge");
        break;
    default:
        break;
}

文献

8
29
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
8
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?