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?
You find yourself with duplicate keywords when you're bidding on the exact same keyword with the exact same match type in a single search campaign more than once. For example, if you're bidding on the exact match keyword [men's blue tennis shoes] twice in one search campaign, you have a duplicate keyword on your hands.
A caveat: you can certainly use the same keyword in multiple ad groups as long as they appear in different campaigns which are targeted in different ways. So, for example, if you have created individual campaigns for each state and geotargeted them, there wouldn't be any conflict, so that's fine.
Redundant keywords are often confused with non-serving keywords. In reality, redundant keywords are the keywords having the same match type and same ad group.
Exceptions can be costly and have an implicit goto
behavior.
I would do case 2 as this and you save yourself some instructions and clarity.
Child result2 = obj as Child;
if(result2 != null)
{
}
else
{
// Handle failed cast
}
Exceptions are rather expensive, so when you expect one you should use logic to avoid throwing in the first place. But neither of your code snippets is recommended style. Try one of these:
// Method 2b
if(obj is Child)
{
Child result2 = (Child)obj;
}
else
{
// Handle failed cast
}
// Method 3:
Child result3 = obj as Child;
if(result3 != null)
{
}
else
{
// Handle failed cast
}
The as
followed by null
also neatly handles the case where obj
was null
to begin with.
You can think of as
vs cast being the same as TryParse
vs Parse
. It lets you handle failure cheaply using normal program flow instead of throwing an exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With