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. ' The example displays the following output:īecause the conversion is not supported, there is no workaround.
The example displays the following output:Ĭonsole.WriteLine("Conversion succeeded.")Ĭonsole.WriteLine("Cannot convert a Boolean to a Char.") using System Ĭonsole.WriteLine("Conversion succeeded.") Ĭonsole.WriteLine("Cannot convert a Boolean to a Char.") In both cases, the method call throws an InvalidCastException exception. 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:
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