逐語的識別子
変数と式 - C# によるプログラミング入門 | ++C++; // 未確認飛行 C
変数を宣言する時に変数名の先頭に「@」をつけるとC#のキーワード名と同名の変数でも宣言することが可能となります。
例えばthisを変数名として使う場合、通常なら以下のエラーがでます。
using System; class Program { static void Main() { int this = 1; Console.WriteLine( this ); } }
$ csc main.cs Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1 Copyright (C) Microsoft Corporation. All rights reserved. main.cs(5,10): error CS1041: 識別子が必要です。キー ワードは 'this' です
@を付けると正しく動作します。
using System; class Program { static void Main() { int @this = 1; Console.WriteLine( @this ); } }
$ main 1
ちなみに通常の変数名であれば@が付いていても付いていなくてもまったく同じ意味になるそうです。
using System; class Program { static void Main() { // @無しで宣言して@有りで表示 int foo = 1; Console.WriteLine( @foo ); // @有りで宣言して@無しで表示 int @bar = 2; Console.WriteLine( bar ); } }
$ main 1 2
なかなか面白い機能ですが、キーワードと同名の変数を定義したいというケースがあまり思い浮かびませんね。