Home
Do you avoid casts and use the "as operator" instead?
  v2.0 Posted at 1/05/2018 4:44 AM by Tiago Araujo
Use casts only if:
a. You know 100% that you get that type back
b. You want to perform a user-defined conversion

​ private void AMControlMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
var auc = (AMUserControl)sender;
var aucSessionId = auc.myUserControl.Tag;
// snip snip snip
}

Bad example​​​

private void AMControlMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
var auc = sender as AMUserControl;
if (auc != null)
{
var aucSessionId = auc.myUserControl.Tag;
// snip snip snip
}
}

​Good example​
More info here: ​http://blog.gfader.com/2010/08/avoid-type-casts-use-operator-and-check.html

Related rules

    Do you feel this rule needs an update?

    If you want to be notified when this rule is updated, please enter your email address:

    Comments:

    Note: Social Media login for Yotpo is not working in IE or Safari, please use Chrome. We are waiting for Yotpo to fix it.