You're probably looking for the is
keyword, with the syntax expression is type
Documentation describes it as performing the checks you want:
An is expression evaluates to true if
both of the following conditions are
met:
• expression is not null.
• expression
can be cast to type. That is, a cast
expression of the form
(type)(expression) will complete
without throwing an exception.
Edit
However, if instead of just working out whether you can cast something before you try, the as keyword is probably your best solution as you describe in your post.
The following code would perform the same function though...
try
{
T result = (T)obj;
return result;
}
catch (InvalidCastException ex)
{
// throw your own exception or deal with it in some other way.
}
Which method you prefer is up to you...