views:

83

answers:

2

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
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
Keep in mind that "as" works only for Reference-Type or Nullable
Carlos Muñoz
Yes because `int?` is equivalent to `Nullable<Int32>` wich is a reference-type
Carlos Muñoz
No, it's a value type, a struct.
Hans Passant
A: 

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

akonsu