System.InvalidCastException: Unable to cast object of type 'X' to type 'Y'
An explicit cast failed because the object’s runtime type isn’t the target type.
Unable to cast object of typeSpecified cast is not valid Meaning
Common with DB values (Int64 vs Int32, DBNull), boxed values, deserialized objects, or two copies of the same type from different assemblies/load contexts.
Common causes
- Casting boxed numeric types (long → int)
- DBNull.Value from a database
- Deserialized JsonElement/JObject instead of the class
- Same type loaded from two assemblies
⚡ Quick fix
- Use Convert.ToInt32 or pattern matching (is T t)
- Check for DBNull
- Deserialize into the concrete type
Detailed fix by platform
C#
- csharp
if (value is long l) id = checked((int)l); var count = reader.IsDBNull(0) ? 0 : Convert.ToInt32(reader.GetValue(0));
How to diagnose
- Types — From/to in the message
- Source — DB, JSON, plugin?
🔧 Still not fixed?
Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:
Similar errors
Most viewed in .NET
- FileNotFoundException assembly Could not load file or assembly 'X, Version=…' or one of its dependencies
- NullReferenceException System.NullReferenceException: Object reference not set to an instance of an object
- Cannot access a disposed context instance ObjectDisposedException: Cannot access a disposed context instance
Other ways to find it
Where this error sits
Origin: Application & API. Errors that are often confused with or caused by this one (click to open):
🧠 Still stuck? Analyze your error
Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.
💬 What worked for others
No tips yet — did something else fix this for you?
Share what worked for you
Tips are checked by an editor before they appear. Links are removed.
Report a correction or suggest an improvement
Last updated 14 Oct 2026