views:

208

answers:

2

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));
            }
        }
    }
}
+13  A: 

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));
}
Jon Skeet
At our company, we refer to this as the "Empty Delegate Pattern"
John Kraft
A: 

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.

Skurmedel
It's just the null object pattern - I don't see why you consider that sloppy.
Jon Skeet