uniblab icon

A better way to cast, As<T>()

uniblab | PRO | 05/14/20 03:41:23 AM UTC | 0 ⭐ | 3534 👁️ | Never ⏰ | []
C# |

920 B

|

None

|

0 👍

/

0 👎

// 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