views:

120

answers:

3

Given the code below:

void LookupBox_Load(object sender, EventArgs e)
{
    Action d = delegate
        {
            if (!_p.AutoClose)
                CloseLookupBox();
        };

    if (this.ParentForm.MdiParent != null)
        this.ParentForm.MdiParent.Deactivate += delegate { d(); };
    else
        this.ParentForm.Deactivate += delegate { d(); };
}

Is there a way to omit the delegate { d(); } ?

void LookupBox_Load(object sender, EventArgs e)
{
    Action<object,EventArgs> d = delegate
        {
            if (!_p.AutoClose)
                CloseLookupBox();
        };

    if (this.ParentForm.MdiParent != null)
        this.ParentForm.MdiParent.Deactivate += d;
    else
        this.ParentForm.Deactivate += d;
}

Note: I want to do this inline

+2  A: 

Not much better, but you could do if you're using C# 3.0:

if (this.ParentForm.MdiParent != null)
    this.ParentForm.MdiParent.Deactivate += (x,y) => d();
else
    this.ParentForm.Deactivate += (x,y) => d();
Deeksy
A: 

You should use EventHandler<MyEventArgs> to define those instead of the Action delegate

  EventHandler<EventArgs> d = delegate        
       {            
            if (!_p.AutoClose)                
               CloseLookupBox();        
       };
Gurdas Nijor
+3  A: 

Absolutely - change the type of d to start with:

EventHandler d = delegate
    {
        if (!_p.AutoClose)
            CloseLookupBox();
    };

Anonymous methods don't just work with Func and Action...

For future reference though, you can create a new delegate based on an existing one with a compatible signature:

Action<object, EventArgs> d = ...;
EventHandler handler = new EventHandler(d);

But this extra indirection is pointless in this case :)

You can also make the code calling it slightly simpler too using the null-coalescing operator:

Form form = ParentForm.MdiParent ?? ParentForm;
form.Deactivate += d;

As you're then only using d once, you could inline it, turning the whole method into:

Form form = ParentForm.MdiParent ?? ParentForm;
form.Deactivate += delegate
{
    if (!_p.AutoClose)
        CloseLookupBox();
};
Jon Skeet
Whoops, you're right; he's using a vanilla EventHandler, so I guess the generic isn't required. Does using the generic incur any penalty performancewise?
Gurdas Nijor
Well you've got to subscribe with the right type, so you'd have to create a nongeneric instance anyway...
Jon Skeet
+1 for null coalesce operator suggestion. your mind can really pick up every program's intent.
Hao