InvalidCastException Class
TOC
Collapse the table of content
Expand the table of content

InvalidCastException Class

 

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

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

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

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

NameDescription
System_CAPS_pubmethodInvalidCastException()

Initializes a new instance of the InvalidCastException class.

System_CAPS_protmethodInvalidCastException(SerializationInfo, StreamingContext)

Initializes a new instance of the InvalidCastException class with serialized data.

System_CAPS_pubmethodInvalidCastException(String)

Initializes a new instance of the InvalidCastException class with a specified error message.

System_CAPS_pubmethodInvalidCastException(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.

System_CAPS_pubmethodInvalidCastException(String, Int32)

Initializes a new instance of the InvalidCastException class with a specified message and error code.

NameDescription
System_CAPS_pubpropertyData

Gets a collection of key/value pairs that provide additional user-defined information about the exception.(Inherited from Exception.)

System_CAPS_pubpropertyHelpLink

Gets or sets a link to the help file associated with this exception.(Inherited from Exception.)

System_CAPS_pubpropertyHResult

Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.(Inherited from Exception.)

System_CAPS_pubpropertyInnerException

Gets the Exception instance that caused the current exception.(Inherited from Exception.)

System_CAPS_pubpropertyMessage

Gets a message that describes the current exception.(Inherited from Exception.)

System_CAPS_pubpropertySource

Gets or sets the name of the application or the object that causes the error.(Inherited from Exception.)

System_CAPS_pubpropertyStackTrace

Gets a string representation of the immediate frames on the call stack.(Inherited from Exception.)

System_CAPS_pubpropertyTargetSite

Gets the method that throws the current exception.(Inherited from Exception.)

NameDescription
System_CAPS_pubmethodEquals(Object)

Determines whether the specified object is equal to the current object.(Inherited from Object.)

System_CAPS_protmethodFinalize()

Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.(Inherited from Object.)

System_CAPS_pubmethodGetBaseException()

When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.(Inherited from Exception.)

System_CAPS_pubmethodGetHashCode()

Serves as the default hash function. (Inherited from Object.)

System_CAPS_pubmethodGetObjectData(SerializationInfo, StreamingContext)

When overridden in a derived class, sets the SerializationInfo with information about the exception.(Inherited from Exception.)

System_CAPS_pubmethodGetType()

Gets the runtime type of the current instance.(Inherited from Exception.)

System_CAPS_protmethodMemberwiseClone()

Creates a shallow copy of the current Object.(Inherited from Object.)

System_CAPS_pubmethodToString()

Creates and returns a string representation of the current exception.(Inherited from Exception.)

NameDescription
System_CAPS_proteventSerializeObjectState

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

An InvalidCastException exception is thrown when the conversion of an instance of one type to another type is not supported. For example, attempting to convert a Char value to a DateTime value throws an InvalidCastException exception. 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.

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

Universal Windows Platform
Available since 4.5
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Return to top
Show:
© 2016 Microsoft