Share via


Troubleshooting Exceptions: System.InvalidCastException

An InvalidCastException exception is thrown when a failure occurs during an explicit reference conversion. Reference conversions are conversions from one reference type to another. While they may change the type of the reference, they never change the type or value of the conversion's target. Casting objects from one type to another is a frequent cause for this exception.

Associated Tips

  • Check source types against destination types to make sure the conversion is valid.
    For information on conversions supported by the system, see Convert.

Remarks

For an explicit reference conversion to be successful, the source value must be Null (Nothing in Visual Basic), or the object type referenced by the source argument must be convertible to the destination type by an implicit reference conversion.

When a Visual Basic 6.0 application with a call to a custom event in a user control is upgraded to a newer version of Visual Basic and run, this exception may occur with the additional information, "Specified cast is not valid." To address this error, find the following line of code in Form1:

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

And replace it with:

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

See Also

Tasks

How to: Use the Exception Assistant

How to: Convert an Object to Another Type in Visual Basic

How to: Implement User-Defined Conversions Between Structs (C# Programming Guide)

Reference

InvalidCastException

Concepts

Converting Strings to .NET Framework Data Types