Search code examples
visual-studiodesign-patternspattern-matchingmessage

"Use pattern matching" Message


Visual Studio gives me the Message:

Use pattern matching

With the Code IDE0020

The Snippet:

private void BTclear_Clicked(object sender, RoutedEventArgs e)
{
  Button BTclear = (Button)sender;
  if (BTclear.DataContext is ObservableCollectionUser)
  {
    ObservableCollectionUser clearMe = (ObservableCollectionUser)BTclear.DataContext;
    Users.Remove(clearMe);
  }
}

The if statement is green underlined.

What does it mean and how can I optimize it?


Solution

  • You can use a type pattern to introduce a new variable of type ObservableCollectionUser without that cast:

    private void BTclear_Clicked(object sender, RoutedEventArgs e)
    {
        Button button = (Button) sender;
        if (button.DataContext is ObservableCollectionUser user)
        {
            Users.Remove(user);
        }
    }
    

    (I renamed BTclear to button to be more idiomatic in terms of naming conventions, but the important part is the introduction of the user variable in the is expression.)

    Note that this isn't really about optimization - it's about the code being clearer and simpler. It may be slightly faster, but it's very unlikely to be significant.