Explicit reference or unboxing casting fails due to incompatible runtime types.
Thrown when an explicit reference conversion or unboxing cast fails at runtime because the actual object instance is not convertible to the target type.
Direct casting `(TargetType)obj` when `obj` is an instance of a different, non-subclass type.
1using System;2 3public class Program {4 public static void Main() {5 object obj = "Hello World";6 int number = (int)obj; // Throws InvalidCastException!7 }8}1using System;2 3public class Program {4 public static void Main() {5 object obj = "Hello World";6 7 // Fix 1: Safe casting with 'as' operator8 string str = obj as string;9 if (str != null) {10 Console.WriteLine($"String value: {str}");11 }12 13 // Fix 2: Pattern matching with 'is' operator14 if (obj is int number) {15 Console.WriteLine($"Number: {number}");16 } else {17 Console.WriteLine("Object is not an integer.");18 }19 }20}Simulate standard system builds to trigger compiler trace records and track memory crashes locally.
Object `obj` stores a `string` at runtime. Attempting to force-cast a `string` to an `int` via `(int)obj` throws an `InvalidCastException`.