Advertisement
uniblab

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

May 13th, 2020
2,486
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.92 KB | None | 0 0
  1. // 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:
  2. someComboBox.Items.Append( new ComboBoxItem { Content = thing.Name, Tag = thing } );
  3.  
  4.  
  5. // accessing the above is often ugly and hard to read:
  6. void OnSelectionChanged( System.Object sender, SelectionChangedEventArgs e ) {
  7.     var thing = (Thing)((ComboBoxItem)((ComboBox)sender).SelectedItem)?.Tag;
  8. }
  9. // notice our eyes had to ping-pong back and forth to make sense of the casting
  10.  
  11.  
  12. // but add just one helper extension method:
  13. public static class Extensions {
  14.     public static T As<T>( this System.Object obj ) where T : class => ( obj as T );
  15. }
  16. void OnSelectionChanged( System.Object sender, SelectionChangedEventArgs e ) {
  17.     var thing = sender.As<ComboBox>().SelectedItem.As<ComboBoxItem>()?.Tag.As<Thing>();
  18. }
  19. // simple, straight-forward, elegant, easy to read because it is now LEFT-TO-RIGHT
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement