#503 – Be Careful When Casting RoutedEventArgs.Source

In an event handler, you’ll often cast the RoutedEventsArgs.Source property to a particular type.  When you have an event handler attached to a panel that can contain controls of various types, this can lead to problems.

In the example below, we’re assuming that the originator of the Click event is a Button.

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button b = e.Source as Button;
            MessageBox.Show(string.Format("You clicked on {0} button, sender is of type {1}",
                b.Content, sender.GetType().ToString()));
        }

If we have a panel that contains some Buttons, but also a ToggleButton control–which has a Click event but is not a Button–we get a crash when clicking on the ToggleButton.

A better solution is to check the type of the originator.

            if (e.Source is Button)
            {
                Button b = e.Source as Button;
                MessageBox.Show(string.Format("You clicked on {0} button, sender is of type {1}",
                    b.Content, sender.GetType().ToString()));
            }
Advertisement