A real use for `as` and `is`

2019-04-19 00:39发布

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?

14条回答
贼婆χ
2楼-- · 2019-04-19 00:54

I use 'as' as a handy shortcut in event handlers to get the sending object back when I can't know at design time the sender.

protected void SomeButtonInAGridView_Click(object sender, EventArgs e)
{
    Button clickedButton = sender as Button;
}
查看更多
萌系小妹纸
3楼-- · 2019-04-19 00:55

Here's another use-case to go into the Cabinet of Dr. Caligari ;-)

You can chain the as operator, as in:

x = obj as Label as Control;

Why would you do such a thing? If you want null if its not a Label, but you want to treat them all as Control. Just casting Textbox and Label directly to Control would yield success for both, now it'll be null for unwanted types of Control. This is a shortcut method you won't need often but is occasionally handy.

An alternative use for the same is when you need ToString() on an object, but only when it is of the correct type, otherwise you want a default string. This is a scenario that I do encounter very often, esp. with POCOs. Because ToString() is virtual, this works:

// assume SomeClass has overridden ToString()
// return "none" if item is not of type SomeClass or if it is null to begin with
string itemText = (item as SomeClass as Object ?? "none").ToString();
查看更多
祖国的老花朵
4楼-- · 2019-04-19 00:56

I used both keywords extensively in a WinForms app where there's a GUI to edit an invoice, each row in the ListView could contain different types of items (i.e., it could be a line item or a description, or ...). All the items I put in the ListView were derived from ListViewItem, so then later on when I went to implement things like editing the selected item, I had to check which item type was selected (using is) to show the appropriate editing GUI.

查看更多
Rolldiameter
5楼-- · 2019-04-19 00:59

Here's one that comes up alot:

class Foo {
     public override bool Equals(object obj)
     {
         // The more specific function needs to do null checking anyway.
         return Equals(obj as Foo);
     }

     public bool Equals(Foo obj)
     {
         // do some comparison here.
     }
}
查看更多
6楼-- · 2019-04-19 01:00

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.

查看更多
Evening l夕情丶
7楼-- · 2019-04-19 01:02

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.

查看更多
登录 后发表回答