Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use cases for 'as' keyword [duplicate]

Tags:

c#

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?

like image 759
Johan Geluk Avatar asked Dec 25 '13 02:12

Johan Geluk


People also ask

What are duplicate keywords?

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.

Can I use the same keywords in different campaigns?

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.

What are redundant keywords?

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.


2 Answers

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
}
like image 118
Daniel A. White Avatar answered Sep 28 '22 05:09

Daniel A. White


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.

like image 27
Ben Voigt Avatar answered Sep 28 '22 05:09

Ben Voigt