Is there a way to check whether a C# cast will be successful? In some cases; based on how a rendered page is put together; inheriting from different Master Pages, some casts will work and others will not. I am wondering how I can check to see if a cast will be successful or if I just have to catch and handle an invalid cast exception.
An InvalidCastException is thrown when cast from one type to another type is not supported. In some reference type conversions , the compiler cannot determine whether a cast will be valid. It is because of the source type cannot be converted to the destination type , so the cast does not succeed.
You can say :
if (Variable is Typename) {
}
Or
Variable = OtherVariable as TypeName;
Variable will be null if casting was not possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With