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 }
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 }
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 }
DictionaryもList同様System.Collections.Genericにあります。コレクション系はまとめてここにまとまっています。
直し方: (空) を using System.Collections.Generic; にします。
パターン4
1 ^ 2 class Program { 3 static void Main(string[] args) { 4 Queue<int> q = new Queue<int>(); 5 q.Enqueue(1); 6 System.Console.WriteLine(q.Count); 7 } 8 }
Queue<T>もSystem.Collections.Genericにあります。usingが無いと型を見つけられません。
直し方: (空) を using System.Collections.Generic; にします。
パターン5
1 ^ 2 class Program { 3 static void Main(string[] args) { 4 Stack<int> s = new Stack<int>(); 5 s.Push(1); 6 System.Console.WriteLine(s.Count); 7 } 8 }
Stack<T>も同じ名前空間です。コレクション系のジェネリック型はここにまとまっています。
直し方: (空) を using System.Collections.Generic; にします。
よくある誤解
List<T>やDictionaryなどのコレクション型は、usingディレクティブがないとコンパイラが見つけられません。C#はJavaのjava.langのような「常に使える」標準クラス群を持ちません。
実務での勘所
C# 10以降・.NET 6以降のプロジェクトでは、ImplicitUsingsという設定を有効にすると、System、System.Linq、System.Collections.Genericなど、ほとんどのプロジェクトで使う代表的な名前空間へのusingが自動的に補われるようになりました。新規プロジェクトのテンプレートでは既定でオンになっています。それでもこのエラーが出る場合は、外部ライブラリなど、暗黙補完の対象に含まれない名前空間を使おうとしていることが多いです。