初級 › Object reference not set エラー(null参照)の原因 › パターン2
Object reference not set エラー(null参照)の原因
C#で最も有名な実行時エラーです。
1 class Program { 2 static void Main(string[] args) { 3 string[] names = new string[3]; 4 names[0] = ______; ^ 5 System.Console.WriteLine(names[0].ToUpper()); 6 } 7 }
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
at Program.Main(String[] args) in Program.cs:line 5
空欄を埋めてビルドを通す
string配列は要素をnullで初期化します。代入し忘れた要素をそのまま使うとNullReferenceExceptionになります。
次の問題