

The following example calls both the and Convert.ToChar(Boolean) methods to convert a Boolean value to a Char. For example, trying to convert a Boolean value to a Char or a DateTime value to an Int32 throws an InvalidCastException exception. You directly or indirectly call a primitive type's IConvertible implementation that does not support a particular conversion. InvalidCastException uses the HRESULT COR_E_INVALIDCAST, which has the value 0x80004002.įor a list of initial property values for an instance of InvalidCastException, see the InvalidCastException constructors. The following intermediate language (IL) instructions throw an InvalidCastException exception: Narrowing conversions and IConvertible implementationsįor 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.



Some of the conditions under which an attempted conversion throws an InvalidCastException exception are discussed in the following sections: In many cases, your language compiler detects that no conversion exists between the source type and the target type and issues a compiler error. 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. Instead, the cause of the exception should be eliminated.įor information about conversions supported by the system, see the Convert class. An InvalidCastException exception is caused by developer error and should not be handled in a try/catch block. 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 example, attempting to convert a Char value to a DateTime value throws an InvalidCastException exception. NET Framework.Īn InvalidCastException exception is thrown when the conversion of an instance of one type to another type is not supported. For more information, see Type Conversion in. It also includes a variety of mechanisms that support custom conversions. 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. SerializableAttribute ComVisibleAttribute Remarks
