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.
Seen on:
.NET
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
- NullReferenceException System.NullReferenceException: Object reference not set to an instance of an object
- FileNotFoundException assembly Could not load file or assembly 'X, Version=…' or one of its dependencies
- InvalidOperationException InvalidOperationException: Unable to resolve service for type 'X' while attempting to activate 'Y'
Other ways to find it
🧠 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.
Was this page helpful?
Report a correction or suggest an improvement
Last updated 7 Oct 2026