Alex Rivera | Logout

A real use for `as` and `is`

Asked 2009-10-15T13:06:31.803
14

I have -never- used as or is in C# or any language that supports the keyword.

What have you used it for?

I dont mean how do i use it i mean how have you actually need it?

I also got away with doing no typecasting in a fairly large c++ project (i was proud).

So considering i almost never typecast why do i need the keyword as or is?

Edit
Report

2 Answers

8

Intriguing question. Actually, I use them all the time. is is handy to find out whether an object is of a certain type, I use that occasionally in generics or in loops through objects that are of different types. It is also invaluable with Reflection.

The other, as finds many more uses. It is often much safer to use then a normal cast: when it fails, it returns null, instead of an exception. I also find it clearer syntax and easier to use it, check the return value for null, then to add an exception block.

Basically, what I mean to say is, I prefer this:

protected void GeneralEventHandler(object sender, EventArgs e)
{
    Button btn = sender as Button;
    if(btn != null)   // click came from a button!
        // do something
    else
        // other cases
}

and this:

protected void GeneralEventHandler(object sender, EventArgs e)
{
    if(sender is Button)   // click came from a button!
        // do something
    else
        // other cases
}

as opposed to this:

protected void GeneralEventHandler(object sender, EventArgs e)
{
    try 
    {
        Button btn = (Button) sender;
        // if we get this far, it's a button
    }
    catch(InvalidCastException ice)
    {
        // click did not come from a button! Handle other cases
    }
}

of course, this is just an example, but when I can avoid try / catch, I will. This also lets more room for real exceptions to get through.

answered 2009-10-15T13:09:58.013
1

C-style casts (like (Foo)bar) will throw InvalidCastException if cast fails. as, on the other hand, will yield null (see this). is operator is just used to test whether a run-time type of given instance is compatible with the type provided (see this).

is is used extensively in.NET System.ComponentModel namespace. More specifically, TypeConverter API relies heavily on is operator to determine how to convert from one type to another.

answered 2009-10-15T13:09:54.130

Your Answer