I'm wondering, in which case would you use C#'s 'as' keyword, as opposed to casting and checking for an exception? Consider this example:
Parent obj = new Child();
// Method 1:
try
{
Child result1 = (Child)obj;
}
catch (InvalidCastException)
{
// Handle failed cast
}
// Method 2:
if(obj is Child)
{
Child result2 = obj as Child;
}
else
{
// Handle failed cast
}
Both Method 1 and Method 2 produce, as far as I'm aware, the exact same result. I know that, when they fail, the as keyword will produce null, while a cast will throw a ClassCastException, but to me, that doesn't seem like enough of a reason to have two nearly identical ways to cast an object. So I'm wondering, why did the C# language designers go trough the trouble of adding the 'as' keyword?