System.InvalidCastException Class

The exception that is thrown for invalid casting or explicit conversion.

See Also: InvalidCastException Members


public class InvalidCastException : SystemException


An InvalidCastException exception is thrown when the conversion of an instance of one type to another type is not supported. It differs from an OverflowException exception, which is thrown when a conversion of one type to another is supported, but the value of the source type is outside the range of the target type.

For information about 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 the OverflowException exception.


In many cases, your language compiler detects that no conversion exists between the source type and the target type and issues a compiler error.

Some of the conditions under which an attempted conversion throws an InvalidCastException exception include the following:

For an explicit reference conversion to be successful, the source value must be null, or the object type referenced by the source argument must be convertible to the destination type by an implicit reference conversion.

The following intermediate language (IL) instructions throw an InvalidCastException exception:

InvalidCastException uses the HRESULT COR_E_INVALIDCAST, which has the value 0x80004002.

For a list of initial property values for an instance of InvalidCastException, see the InvalidCastException.#ctor constructors.

Thread Safety

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


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


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


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