Unable to cast object of type 🟪 .NET

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

  1. Use Convert.ToInt32 or pattern matching (is T t)
  2. Check for DBNull
  3. Deserialize into the concrete type

Detailed fix by platform

C#

  1. csharp
    if (value is long l) id = checked((int)l);
    var count = reader.IsDBNull(0) ? 0 : Convert.ToInt32(reader.GetValue(0));

How to diagnose

  1. Types — From/to in the message
  2. 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:

🧠 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.