8
9

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 5 years have passed since last update.

C#でキーワード(予約語)を変数名として使うには

Last updated at Posted at 2015-05-18

(あまり役に立たないChipsです。)
推奨されていませんが可能です。ただし、予約語そのものを使うことはできません。予約語の前に @ を付けると変数とみなされます。コンテキストキーワード (*1) は @ を付けずに変数名として使える場合があります。

(参考) VB.NET では [ ] で囲むと予約語を変数とみなします。


using System;

public class EscapedName
{
  public static void Main()
  {
    var @if = 0;
    var @else = 1;
    var @switch = 2;
    var value = 3;
    var set = 4;
    var get = 5;
    
    Console.WriteLine(@if);
    Console.WriteLine(@else);
    Console.WriteLine(@switch);
    Console.WriteLine(value);
    Console.WriteLine(set);
    Console.WriteLine(get);
  }
}
*1 コンテキストキーワードとはプログラムの文脈内で特別な意味を持つキーワードです。例えば、value はプロパティの set メソッド内だけで特別な意味を持ちます。コンテキストキーワードには以下のようなものがあります (C# 4.0 の場合)。

    add
    alias
    ascending
    async
    await
    descending
    dynamic
    From
    get
    global
    group
    into
    join
    let
    orderby
    partial (型)
    partial (メソッド)
    remove
    Select
    Set
    value
    var
    where (ジェネリック型制約)
    where (クエリ句)
    yield

@ はメソッド名とかにも使用できるようです。次のサンプルは @if というメソッドを定義して使っています。

using System;

public class IIf
{
  // Ruby や Perl の "文 if 条件" のようなメソッド
  public static void @if(bool b, Action act)
  {
     if (b) { act(); }
  }

  public static void Main()
  {
     for (int i = 0; i < 5; i++)
     {
        @if(i % 2 == 0, ()=>{ Console.WriteLine(i); });
     }
  }
}
8
9
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
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?