This program shows an InvalidCastException being thrown. This is generated when a statement tries to cast one reference type to another type that is not compatible.
Info Casts that use the type name in parentheses are called explicit casts. Usually this exception indicates a coding error.
Tip It is possible to remedy this by defining a custom explicit cast method, but not usually recommended.
Detail Avoiding casting (by using generics or objects) is usually the best. This may help performance and code readability.
static void Main()
// Creates a new object instance of type StringBuilder.
// ... Then uses implicit cast to object through assignment.
// ... Then tries to use explicit cast to StreamReader, but fails.
StringBuilder reference1 = new StringBuilder();
object reference2 = reference1;
StreamReader reference3 = (StreamReader)reference2;
}Unhandled Exception: System.InvalidCastException:
Unable to cast object of type 'System.Text.StringBuilder' to type 'System.IO.StreamReader'.
at Program.Main() in ...Program.cs:line 13
Notes, example steps. The first reference is of type StringBuilder. Then an object type is assigned to the StringBuilder reference, providing an implicit conversion to object type.