Mono Class Library: System Namespace

System.InvalidCastException Class

Represents the error that occurs when an explicit conversion (casting operation) fails because the source type cannot be converted to the destination type. [Edit]

See Also: InvalidCastException Members

System.Object
     System.Exception
          System.SystemException
               System.InvalidCastException

[System.Runtime.InteropServices.ComVisible(true)]
public class InvalidCastException : SystemException

Thread Safety

All public static members of this type are safe for multithreaded operations. No instance members are guaranteed to be thread safe.

Remarks

Note:

For information on conversions supported by the system, see the Convert class.

For errors that occur when the destination type can store source type values, but is not large enough to store a specific source value, see OverflowException exception.

The following CIL instructions throw InvalidCastException:

  • castclass
  • refanyval
  • unbox
[Edit]

Example

The following example demonstrates an error that causes a InvalidCastException exception.

C# Example
using System;
public class InvalidCastExample {
 public static void Main() {
   object obj = new Object();
   int i;
   try {
     i = (int) obj;
   }
   catch( InvalidCastException e ) {
     Console.WriteLine("Caught: {0}", e);
   }
 }
}
   

The output is

Example
Caught: System.InvalidCastException: Specified cast is not valid.
   at InvalidCastExample.Main()
			

Requirements

Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0