Code Fix

初級

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 にします。

この問題を解いてみる →

パターン4

 1  class Program {
 2      static void Main(string[] args) {
 3          int score = 88;
 4          System.Console.WriteLine(scroe);
                                       ^
 5      }
 6  }
Program.cs(4,34): error CS0103: The name 'scroe' does not exist in the current context

scoreのタイプミスであるscroeは宣言されていないため、未知の識別子として扱われます。

直し方: scroe を score にします。

この問題を解いてみる →

パターン5

 1  class Program {
 2      static int Cube(int n) { return n * n * n; }
 3      static void Main(string[] args) {
 4          System.Console.WriteLine(Cub (2));
                                       ^
 5      }
 6  }
Program.cs(4,34): error CS0103: The name 'Cub' does not exist in the current context

メソッド名のスペルミスです。定義した名前と1文字でも違うと見つけられません。

直し方: Cub を Cube にします。

この問題を解いてみる →

よくある誤解

変数はそれを宣言したブロック({ }の中)を出ると存在しなくなります。ブロックの外で使おうとしても「存在しない」というエラーになります。

実務での勘所

C#のブロックスコープは終始一貫しており、JavaScriptのvarのような「宣言した関数全体に持ち上がる」例外はありません。ただし、ローカル関数やラムダ式は、自分の外側のスコープにある変数を自由に参照できる(キャプチャする)一方、その逆(ローカル関数やラムダの内部だけで宣言した変数)は外側から参照できません。「内側から外側は見えるが、外側から内側は見えない」という一方通行の関係を意識しておくと、スコープに関するエラーの見通しが良くなります。

演習をはじめる

関連するエラー

広告
広告スロット(未設定)