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 ref 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.)

The .NET Framework supports automatic conversion from derived types to their base types and back to the derived type, as well as from types that present interfaces to interface objects and back. It also includes a variety of mechanisms that support custom conversions. For more information, see Type Conversion in the .NET Framework.

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. An InvalidCastException exception is caused by developer error and should not be handled in a try/catch block; instead, the cause of the exception should be eliminated.

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 are discussed in the following sections:

Primitive types and IConvertible
The Convert.ChangeType method
Narrowing conversions and IConvertible implementations
Downcasting
Conversion from an interface object
String conversions
Visual Basic 6.0 migration

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.

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.

No code example is currently available or this language may not be supported.

Because the conversion is not supported, there is no workaround.

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.

In most cases, because the conversion is not supported, there is no workaround. In some cases, a possible workaround is to manually assign property values from the source type to similar properties of a the target type.

Narrowing operators define the explicit conversions supported by a type. A casting operator in C# or the CType conversion method in Visual Basic (if Option Strict is on) is required to perform the conversion.

However, if 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, an InvalidCastException exception is thrown.

In most cases, because the conversion is not supported, there is no workaround.

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.

No code example is currently available or this language may not be supported.

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.

You are attempting to convert an interface object to a type that implements that interface, but the target type is not the same type or a base class of the type from which the interface object was originally derived. The following example throws an InvalidCastException exception when it attempts to convert an IFormatProvider object to a DateTimeFormatInfo object. The conversion fails because although the DateTimeFormatInfo class implements the IFormatProvider interface, the DateTimeFormatInfo object is not related to the CultureInfo class from which the interface object was derived.

No code example is currently available or this language may not be supported.

As the exception message indicates, the conversion would succeed only if the interface object is converted back to an instance of the original type, in this case a CultureInfo. The conversion would also succeed if the interface object is converted to an instance of a base type of the original type.

You are trying to convert a value or an object to its string representation by using a casting operator in C#. In the following example, both the attempt to cast a Char value to a string and the attempt to cast an integer to a string throw an InvalidCastException exception.

using System;

public class Example
{
   public static void Main()
   {
      object value = 12;
      // Cast throws an InvalidCastException exception.
      string s = (string) value;
   }
}
System_CAPS_noteNote

Using the Visual Basic CStr operator to convert a value of a primitive type to a string succeeds. The operation does not throw an InvalidCastException exception.

To successfully covert an instance of any type to its string representation, call its ToString method, as the following example does. The ToString method is always present, since the ToString method is defined by the Object class and therefore is either inherited or overridden by all managed types.

using System;

public class Example
{
   public static void Main()
   {
      object value = 12;
      string s = value.ToString();
      Console.WriteLine(s);
   }
}
// The example displays the following output:
//      12

You're upgrading a Visual Basic 6.0 application with a call to a custom event in a user control to Visual Basic .NET, and an InvalidCastException exception is thrown with the message, "Specified cast is not valid." To eliminate this exception, change the line of code in your form (such as Form1)

Call UserControl11_MyCustomEvent(UserControl11, New UserControl1.MyCustomEventEventArgs(5))

and replace it with the following line of code:

Call UserControl11_MyCustomEvent(UserControl11(0), New UserControl1.MyCustomEventEventArgs(5))

Universal Windows Platform
Available since 8
.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: