C# Reference ยท Exceptions and Diagnostics
InvalidCastException
Reference for InvalidCastException in C#: failing explicit casts, unboxing the wrong type, and how as, is, pattern matching and Convert avoid it.
InvalidCastException is thrown at runtime when an explicit cast or conversion is not valid for the actual object. The compiler allows (Dog)animal because a Dog might be an Animal, but if the object really is a Cat, the cast fails. The same happens when you unbox a value to the wrong type, or when Convert or IConvertible has no conversion for a pair of types.
Check with is or use as and pattern matching, so a mismatch becomes a normal false or null rather than an exception. Generics remove most casts in the first place.
object o = "text"; if (o is string s) { Console.WriteLine(s.Length); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public class InvalidCastException : SystemException { public InvalidCastException(); public InvalidCastException(string? message); public InvalidCastException(string? message, Exception? innerException); } (T)expression // throws InvalidCastException on failure expression as T // null on failure (reference or nullable types) expression is T name // false on failure, binds name on success
| Form | On a mismatch |
|---|---|
(T)x |
Throws InvalidCastException. A null reference casts fine to a reference type, but unboxing null to a value type throws NullReferenceException. |
x as T |
Evaluates to null. Not usable for non-nullable value types. |
x is T t |
The condition is false. |
Convert.ChangeType |
Throws if no conversion exists. |
Usage notes
- Unboxing is strict. A boxed
intcan only be unboxed asint(orint?), notlong,doubleor an enum of another type. Unbox first, then convert numerically. - Numeric casts do not throw this.
(int)3.7is a built-in conversion that truncates; overflow behavior is governed bychecked. - User-defined conversions run for
(T)xwhen declared, and they can throw their own exceptions. See Conversion operators. - Interfaces. Casting an object to an interface it does not implement fails at runtime with this exception, unless the compiler can already prove the cast is impossible.
- Prefer pattern matching.
ispatterns andswitchexpressions combine the check and the cast, and the compiler checks exhaustiveness. - Avoid
objectcollections. Non-generic collections such asArrayListforce casts; useList<T>. - Casts and generics.
(T)(object)valueworks in generic code but boxes; prefer generic math or constraints. - Catch rarely. A failing cast is nearly always a design problem; fix the types.