0

This code works. But noticing the similarity between the 6th & 10th line,

void someThing_Click(object sender, RoutedEventArgs e)
{
    President pres;                
    if (e.GetType() == typeof(MouseButtonEventArgs))
    {
         pres = (sender as SomeUserControl ).DataContext as President;
    }
    else
    {
         pres = (sender as MenuItem ).DataContext as President;
    }
}

is there a way to shorten the code like,

Type t = (e.GetType() == typeof(MouseButtonEventArgs)) ? SomeUserControl : MenuItem;
pres = (sender as t).DataContext as President;

the code above doesn't work, just for illustration.

SAm
  • 2,154
  • 28
  • 28
  • 2
    Use "as" operator only if you will check the result of it. In other cases, you should use normal cast (Type) operator - it has better performance. – GrzegorzM Apr 10 '14 at 11:40
  • "normal"(direct) cast isn't faster, internally it uses combination of [is] and [as] operators. please have a look at my comment to @xxMUROxx answer – Andrew Apr 10 '14 at 11:50

3 Answers3

4

I think no need of checking type of event args and all, this should be enough

President pres = ((FrameworkElement)sender).DataContext as President;
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
2

DataContext property is of class FrameworkElement i.e. your SomeUserControl and MenuItem inherit from FrameworkElement. So you can type cast it to FrameworkElement directly:

pres = ((FrameworkElement)sender).DataContext as President;
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
2

Directly use DataContext from FrameworkElement

var fe = sender as FrameworkElement
if(fe != null)
{
    President pres = fe.DataContext as President;
}
Michael Mairegger
  • 6,833
  • 28
  • 41
  • Combination of [as] and comparison with null is the most effective way of doing certain type job with untyped object.(direct cast first checks with [is] and then either throws exception or returns object casted with the use of [as] operator, that is one extra [is] operation) – Andrew Apr 10 '14 at 11:48
  • @Andrew Point 1 agreed, but I disagree that `direct cast first checks with [is] and then either throws exception or returns object casted with the use of [as] operator, that is one extra [is] operation` can you show a official documentation for this? Or any provable link? – Sriram Sakthivel Apr 10 '14 at 11:52
  • for example here: http://stackoverflow.com/questions/496096/casting-vs-using-the-as-keyword-in-the-clr direct cast is internally translated to `if (variable is T){ return (variable as T)} throw.... ` – Andrew Apr 10 '14 at 12:01
  • I did some maths(kind of load test) in the past...try doing the same: a million of direct cast operations versus million of [is]-[as] combinations – Andrew Apr 10 '14 at 12:07
  • another good one: http://www.codeproject.com/Articles/8052/Type-casting-impact-over-execution-performance-in – Andrew Apr 10 '14 at 12:10