Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid a InvalidCastException in .NET?

Tags:

c#

.net

casting

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.

like image 303
Matt Avatar asked Aug 16 '10 19:08

Matt


People also ask

What is InvalidCastException in C#?

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.


1 Answers

You can say :

if (Variable is Typename) { 
}

Or

  Variable = OtherVariable as TypeName;

Variable will be null if casting was not possible.

like image 198
Julian de Wit Avatar answered Sep 24 '22 13:09

Julian de Wit