In my experience, I have found it to be a good idea to use
the casting operator when it should be unlikely for the casting to fail. This
way if there is a problem we definitely know about the error and handle the
situation. When deciding whether to catch or check for exceptions, it is
important to consider the likelihood of the error occurring. If the error is
likely, check for it, and if the error is a problem and not just bad user input
or something similar, handle it by catching the thrown exception.
Since the "as" operator is able to handle things
safely, it should generally be used when you will not be certain if the value
of the object to be converted will cast correctly. Since we are saying in this
case it is not irregular for the object to be an invalid type, it is much
better for the software to handle the problem safely by using "as,"
which ensures the correct type without using exception handling.
According to Microsoft's documentation, using the
"as" operator is equivalent to using the following code, except that
the "expression" defined in the snippet is only evaluated once.
Listing 3: "as" Operator Equivalent Code
expression is type ? (type)expression : (type)null
The "expression" there could be any expression we
were using to cast as a different type, so for the simplicity of the previous
explanation it is the original object we are casting to the new type. The
following is an example situation. Keep in mind that we do not have a
performance decrease here for evaluating the expression twice, because the
"as" operator will only evaluate it one time.