Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ReSharper recommend using "as" keyword instead of "is"? [duplicate]

I using Resharper 8 and when I wrote

if (sender is Button) 

Resharper reclaim to use as keyword and change it to:

Button button = sender as Button;
if (button != null)

There’s any particular reason?

are using as is real better then is? or in this case as is better?

like image 591
Akrem Avatar asked Dec 26 '22 08:12

Akrem


1 Answers

as is arguably better if the resulting expression is used later on; is is just as good if not. E.g.

if (sender is Button) {
    Button button = (Button)sender;  // just use `as`, as suggested
    button.Push();

(I thought ReSharper only gave a warning/hint in the case where a duplicate cast could be eliminated, such as this..)

That being said, I use the structure

Button button;
if ((button = sender as Button) != null) {
    button.Push();

to ensure that the variable is initialized in (and only starting in) the condition - this defers the application of as to the appropriate conditional expression and allows C#/ReSharper to detect some incorrect [uninitialized] variable usage cases.


See also:

Casting vs using the 'as' keyword in the CLR - Jon's answer has 'is/(cast)' pairings as a "don't do" raising concerns with both shared and field vs. property access. Performance and 'is' vs 'as' differences are also discussed.

And a duplicate Which code is better: using "as" or "is"?, with some better related links.

like image 92
user2864740 Avatar answered Apr 27 '23 06:04

user2864740