Code Fix

初級

type or namespace name could not be found の原因と直し方

List<T>やDictionary、StringBuilderなど、名前空間ごとに分かれたクラスを使うにはusingディレクティブが必要です。

エラーメッセージの読み方

Program.cs(4,9): error CS0246: The type or namespace name 'List<>' could not be found (are you missing a using directive or an assembly reference?)
Program.cs
ファイル名
4
行番号
9
列番号 — この位置でコンパイラが解析に失敗しました
CS0246
エラーコード — 検索するとMicrosoftの解説ページが見つかります
The type or namespace name 'List<>' could not be found (are you missing a using directive or an assembly reference?)
内容 — 期待していたもの、または受け付けられなかったもの

このエラーが出る典型パターン

パターン1

 1                                    
                     ^
 2  class Program {
 3      static void Main(string[] args) {
 4          List<int> nums = new List<int>();
 5          nums.Add(1);
 6          System.Console.WriteLine(nums.Count);
 7      }
 8  }
Program.cs(4,9): error CS0246: The type or namespace name 'List<>' could not be found (are you missing a using directive or an assembly reference?)

List<T>はSystem.Collections.Generic名前空間にあります。usingディレクティブがないとコンパイラは型を見つけられません。

直し方: (空)using System.Collections.Generic; にします。

この問題を解いてみる →

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

パターン2

 1                            
                 ^
 2  class Program {
 3      static void Main(string[] args) {
 4          StringBuilder sb = new StringBuilder();
 5          sb.Append("Hi");
 6          System.Console.WriteLine(sb.ToString());
 7      }
 8  }
Program.cs(4,9): error CS0246: The type or namespace name 'StringBuilder' could not be found (are you missing a using directive or an assembly reference?)

StringBuilderはSystem.Text名前空間にあります。文字列操作系のクラスをまとめてここに置いています。

直し方: (空)using System.Text; にします。

この問題を解いてみる →

パターン3

 1                                   
                    ^
 2  class Program {
 3      static void Main(string[] args) {
 4          Dictionary<string, int> scores = new Dictionary<string, int>();
 5          scores["a"] = 1;
 6          System.Console.WriteLine(scores.Count);
 7      }
 8  }
Program.cs(4,9): error CS0246: The type or namespace name 'Dictionary<,>' could not be found (are you missing a using directive or an assembly reference?)

DictionaryもList同様System.Collections.Genericにあります。コレクション系はまとめてここにまとまっています。

直し方: (空)using System.Collections.Generic; にします。

この問題を解いてみる →

よくある誤解

List<T>やDictionaryなどのコレクション型は、usingディレクティブがないとコンパイラが見つけられません。C#はJavaのjava.langのような「常に使える」標準クラス群を持ちません。

まとめ

type or namespace name could not be foundは初級でつまずきやすい項目です。上の3パターンを実際に手で直すと、エラーメッセージのどこを読めばよいかが掴めます。

演習をはじめる

関連するエラー

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