How can I avoid InvalidCastException in .NET?

Is there a way to check if a C # cast will succeed? In some cases; based on how the created page is combined; inheriting from different Master pages, some ghosts will work, while others will not. I am wondering how I can check if the tide is successful, or if I just need to catch and handle an invalid casting exception.

+7
casting c #
source share
2 answers

You can say:

if (Variable is Typename) { } 

Or

  Variable = OtherVariable as TypeName; 

The variable will be empty if casting is not possible.

+20
source share

alternatively, you can use the how keyword to cast and check if the result is null.

0
source share

All Articles