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.
+10
A:
You can say :
if (Variable is Typename) {
}
Or
Variable = OtherVariable as TypeName;
Variable will be null if casting was not possible.
Julian de Wit
2010-08-16 19:18:53
Heh, I actually knew that -- I'll blame it on Monday. Thanks, I will accept answer as soon as the SO let's me. :-)
Matt
2010-08-16 19:20:56
Keep in mind that "as" works only for Reference-Type or Nullable
Carlos Muñoz
2010-08-16 19:21:20
Yes because `int?` is equivalent to `Nullable<Int32>` wich is a reference-type
Carlos Muñoz
2010-08-16 19:29:01
No, it's a value type, a struct.
Hans Passant
2010-08-16 19:45:41
A:
alternatively, you can use "as" keyword to cast and check if the result is null.
akonsu
2010-08-16 19:20:54