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?
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.
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