Export (0) Print
Expand All

InvalidCastException Class

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

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

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

[SerializableAttribute]
[ComVisibleAttribute(true)]
public class InvalidCastException : SystemException

The InvalidCastException type exposes the following members.

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsInvalidCastException()Initializes a new instance of the InvalidCastException class.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsInvalidCastException(String)Initializes a new instance of the InvalidCastException class with a specified error message.
Protected methodInvalidCastException(SerializationInfo, StreamingContext)Initializes a new instance of the InvalidCastException class with serialized data.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsInvalidCastException(String, Exception)Initializes a new instance of the InvalidCastException class with a specified error message and a reference to the inner exception that is the cause of this exception.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsInvalidCastException(String, Int32)Initializes a new instance of the InvalidCastException class with a specified message and error code.
Top

  NameDescription
Public propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsDataGets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsHelpLinkGets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsHResultGets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsInnerExceptionGets the Exception instance that caused the current exception. (Inherited from Exception.)
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsMessageGets a message that describes the current exception. (Inherited from Exception.)
Public propertySupported by Portable Class LibrarySupported in .NET for Windows Store appsSourceGets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsStackTraceGets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public propertyTargetSiteGets the method that throws the current exception. (Inherited from Exception.)
Top

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetBaseExceptionWhen overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetObjectDataWhen overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetTypeGets the runtime type of the current instance. (Inherited from Exception.)

In XNA Framework 3.0, this member is inherited from Object.GetType().


In Portable Class Library Portable Class Library, this member is inherited from Object.GetType().


In .NET for Windows Store apps Windows 8, this member is inherited from Object.GetType().
Protected methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsToStringCreates and returns a string representation of the current exception. (Inherited from Exception.)
Top

  NameDescription
Protected eventSerializeObjectStateOccurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top

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.

NoteNote

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:

  • You directly or indirectly call a primitive type's IConvertible implementation that does not support a particular conversion. For example, trying to convert a Boolean value to a Char or a DateTime value to an Int32 throws an InvalidCastException exception. The following example calls both the Boolean.IConvertible.ToChar and Convert.ToChar(Boolean) methods to convert a Boolean value to a Char. In both cases, the method call throws an InvalidCastException exception.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          bool flag = true;
          try {
             IConvertible conv = flag;
             Char ch = conv.ToChar(null);
             Console.WriteLine("Conversion succeeded.");
          }   
          catch (InvalidCastException) {   
             Console.WriteLine("Cannot convert a Boolean to a Char.");
          }
    
          try {
             Char ch = Convert.ToChar(flag);
             Console.WriteLine("Conversion succeeded.");
          }   
          catch (InvalidCastException) {   
             Console.WriteLine("Cannot convert a Boolean to a Char.");
          }
       }
    }
    // The example displays the following output: 
    //       Cannot convert a Boolean to a Char. 
    //       Cannot convert a Boolean to a Char.
    
  • You've called the Convert.ChangeType method to convert an object from one type to another, but one or both types don't implement the IConvertible interface.

  • Neither the source type nor the target type defines an explicit or narrowing conversion between the two types, and the IConvertible implementation of one or both types doesn't support a conversion from the source type to the target type.

  • You are downcasting, that is, trying to convert an instance of a base type to one of its derived types. In the following example, trying to convert a Person object to a PersonWithID object fails.

    using System;
    
    public class Person
    {
       String _name;
    
       public String Name 
       { 
          get { return _name; }
          set { _name = value; }
       }
    }
    
    public class PersonWithId : Person
    {
       String _id;
    
       public string Id
       {
          get { return _id; }
          set { _id = value; }
       }
    }
    
    public class Example
    {
       public static void Main()
       {
          Person p = new Person();
          p.Name = "John";
          try {
             PersonWithId pid = (PersonWithId) p;
             Console.WriteLine("Conversion succeeded.");
          }   
          catch (InvalidCastException) {
             Console.WriteLine("Conversion failed.");
          } 
    
          PersonWithId pid1 = new PersonWithId();
          pid1.Name = "John";
          pid1.Id = "246";
          Person p1 = pid1;
          try {   
             PersonWithId pid1a = (PersonWithId) p1;
             Console.WriteLine("Conversion succeeded.");
          }   
          catch (InvalidCastException) {
             Console.WriteLine("Conversion failed.");
          } 
    
          Person p2 = null;
          try {   
             PersonWithId pid2 = (PersonWithId) p2;
             Console.WriteLine("Conversion succeeded.");
          }   
          catch (InvalidCastException) {
             Console.WriteLine("Conversion failed.");
          } 
       }
    }
    // The example displays the following output: 
    //       Conversion failed. 
    //       Conversion succeeded. 
    //       Conversion succeeded.
    

    As the example shows, the downcast succeeds only if the Person object was created by an upcast from a PersonWithId object to a Person object, or if the Person object is null.

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:

  • castclass

  • refanyval

  • unbox

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

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone 8, Silverlight 8.1

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft