does not exist in the current context の原因と直し方
変数名のスペルミスやスコープ外参照で出る、初心者に最も身近なエラーの一つです。
エラーメッセージの読み方
Program.cs(4,34): error CS0103: The name 'coutn' does not exist in the current context
Program.cs- ファイル名
4- 行番号
34- 列番号 — この位置でコンパイラが解析に失敗しました
CS0103- エラーコード — 検索するとMicrosoftの解説ページが見つかります
The name 'coutn' does not exist in the current context- 内容 — 期待していたもの、または受け付けられなかったもの
このエラーが出る典型パターン
パターン1
1 class Program { 2 static void Main(string[] args) { 3 int count = 5; 4 System.Console.WriteLine(coutn); ^ 5 } 6 }
Program.cs(4,34): error CS0103: The name 'coutn' does not exist in the current context
変数名のスペルミスです。C#は大文字小文字を区別するため、Countとcountも別の名前として扱われます。
直し方: coutn を count にします。
広告
広告スロット(未設定)
パターン2
1 class Program { 2 static void Main(string[] args) { 3 if (true) { 4 int total = 100; 5 } 6 System.Console.WriteLine(total ); ^ 7 } 8 }
Program.cs(6,34): error CS0103: The name 'total' does not exist in the current context
ブロック内で宣言した変数はそのブロックを出ると存在しません。スコープの外からは参照できません。
直し方: total を 0 にします。
パターン3
1 class Program { 2 static int Square(int n) { return n * n; } 3 static void Main(string[] args) { 4 System.Console.WriteLine(Squar (4)); ^ 5 } 6 }
Program.cs(4,34): error CS0103: The name 'Squar' does not exist in the current context
メソッド名のスペルミスです。定義したメソッド名と1文字でも違うと見つけられません。
直し方: Squar を Square にします。
よくある誤解
変数はそれを宣言したブロック({ }の中)を出ると存在しなくなります。ブロックの外で使おうとしても「存在しない」というエラーになります。
まとめ
does not exist in the current contextは初級でつまずきやすい項目です。上の3パターンを実際に手で直すと、エラーメッセージのどこを読めばよいかが掴めます。