Unable to cast object の原因と直し方
object型に格納された値型(ボックス化)を、元の型と異なる型でアンボックスしようとすると発生します。
エラーメッセージの読み方
Unhandled exception. System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.Int64'.
System- 名前空間 — System なら標準の基本例外です
InvalidCastException- 例外クラス — 何が起きたか。ここを検索するのが最短です
Unable to cast object of type 'System.Int32' to type 'System.Int64'.- 詳細メッセージ — どの値が問題だったか
at Program.Main(String[] args) in Program.cs:line 4- 発生箇所 — スタックトレースの先頭行
このエラーが出る典型パターン
パターン1
1 class Program { 2 static void Main(string[] args) { 3 object obj = 10; 4 var n = (long )obj; ^ 5 System.Console.WriteLine(n); 6 } 7 }
Unhandled exception. System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.Int64'.
at Program.Main(String[] args) in Program.cs:line 4
ボックス化された値は、元の型と完全に一致する型にしかアンボックスできません。intをlongとして取り出すことはできません。
直し方: long を int にします。
広告
広告スロット(未設定)
パターン2
1 class Program { 2 static void Main(string[] args) { 3 object obj = 3.14; 4 var n = (int )obj; ^ 5 System.Console.WriteLine(n); 6 } 7 }
Unhandled exception. System.InvalidCastException: Unable to cast object of type 'System.Double' to type 'System.Int32'.
at Program.Main(String[] args) in Program.cs:line 4
doubleとしてボックス化された値をintとして直接アンボックスすることはできません。数値の変換とアンボックスは別物です。
直し方: int を double にします。
パターン3
1 class Program { 2 static void Main(string[] args) { 3 object obj = true; 4 var n = (int )obj; ^ 5 System.Console.WriteLine(n); 6 } 7 }
Unhandled exception. System.InvalidCastException: Unable to cast object of type 'System.Boolean' to type 'System.Int32'.
at Program.Main(String[] args) in Program.cs:line 4
boolとしてボックス化された値をintとして取り出すこともできません。C#のboolはintの別名ではありません。
直し方: int を bool にします。
よくある誤解
int→longのような暗黙の数値変換は普段は自動で行われますが、アンボックスの際は元の型と完全に一致していないと失敗します。数値変換とアンボックスは別の規則です。
まとめ
Unable to cast objectは中級でつまずきやすい項目です。上の3パターンを実際に手で直すと、エラーメッセージのどこを読めばよいかが掴めます。