Unable to cast object of type .NET Origin: Application & API Last updated 14 Oct 2026

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.

Exact message you may see Unable to cast object of typeSpecified cast is not valid
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:

Where this error sits

Origin: Application & API. Errors that are often confused with or caused by this one (click to open):

ArithmeticException — java.lang.ArithmeticException: / by zero (Java)ArithmeticExceptionArray to string conversion — Warning: Array to string conversion (PHP)Array to string conve…AttributeError — AttributeError: 'X' object has no attribute 'y' (Python)AttributeErrorCannot convert value of type — Swift: Cannot convert value of type 'X' to expected argument type 'Y' (iOS)Cannot convert value …Cannot use object as array — Fatal error: Uncaught Error: Cannot use object of type stdClass as array (PHP)Cannot use object as …ClassCastException — java.lang.ClassCastException: class A cannot be cast to class B (Java)ClassCastExceptionCould not cast value of type — Swift: Could not cast value of type 'X' to 'Y' (iOS)Could not cast value …E0308 — Rust: error[E0308]: mismatched types — expected `X`, found `Y` (Rust)E0308Unable to…

Explore the map of this error Full error map →

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