Tutorial :C# Delegate problem - what the heck does this code do?



Question:

Can anyone explain to me what the following line of C# code does?

public event EventHandler<DataEventArgs<BusinessEntities.Employee>> EmployeeSelected = delegate { };  

The bit that's really got me stumped is the delegate { } piece at the end. For a bit more context, the sample from the EmployeesListView.xaml.cs in the ViewInjection sample that ships with PRISM 2. The full class definition is shown below:

/// <summary>  /// Interaction logic for EmployeesListView.xaml  /// </summary>  public partial class EmployeesListView : UserControl, IEmployeesListView  {      public EmployeesListView()      {          InitializeComponent();      }        public ObservableCollection<BusinessEntities.Employee> Model      {          get { return this.DataContext as ObservableCollection<BusinessEntities.Employee>; }          set { this.DataContext = value; }      }        public event EventHandler<DataEventArgs<BusinessEntities.Employee>> EmployeeSelected = delegate { };        private void EmployeesList_SelectionChanged(object sender, SelectionChangedEventArgs e)      {          if (e.AddedItems.Count > 0)          {              BusinessEntities.Employee selected = e.AddedItems[0] as BusinessEntities.Employee;              if (selected != null)              {                  EmployeeSelected(this, new DataEventArgs<BusinessEntities.Employee>(selected));              }          }      }  }  


Solution:1

This bit:

delegate {}  

just creates a "no-op" delegate of the appropriate type. That delegate is then assigned to the backing variable for the event. It's a simple way to avoid having to do null checks when raising an event - you always have at least one handler, which is the no-op handler.

It means that this code can be simple:

EmployeeSelected(this, new DataEventArgs<BusinessEntities.Employee>(selected));  

Instead of:

EventHandler<DataEventArgs<BusinessEntities.Employee>> handler =EmployeeSelected;  if (handler != null)  {      handler(this, new DataEventArgs<BusinessEntities.Employee>(selected));  }  


Solution:2

It's setting it to an anonymous method that does nothing basically. Why I'm not sure, maybe to avoid a check or something but I would consider that quite sloppy.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »