// assume we have a drop-down list (ComboBox) and we want to access the Tag property of the selected item, which is of type Thing:
someComboBox.Items.Append( new ComboBoxItem { Content = thing.Name, Tag = thing } );
// accessing the above is often ugly and hard to read:
void OnSelectionChanged( System.Object sender, SelectionChangedEventArgs e ) {
var thing = (Thing)((ComboBoxItem)((ComboBox)sender).SelectedItem)?.Tag;
}
// notice our eyes had to ping-pong back and forth to make sense of the casting
// but add just one helper extension method:
public static class Extensions {
public static T As<T>( this System.Object obj ) where T : class => ( obj as T );
}
void OnSelectionChanged( System.Object sender, SelectionChangedEventArgs e ) {
var thing = sender.As<ComboBox>().SelectedItem.As<ComboBoxItem>()?.Tag.As<Thing>();
}
// simple, straight-forward, elegant, easy to read because it is now LEFT-TO-RIGHT
Comments