Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short way to write an event?

Tags:

c#

events

Typically we use this code:

    private EventHandler _updateErrorIcons;
    public event EventHandler UpdateErrorIcons
    {
        add { _updateErrorIcons += value; }
        remove { _updateErrorIcons -= value; }
    }

Is there a similar shortcut like with automatic properties? Something like:

   public event EventHandler UpdateErrorIcons { add; remove; }
like image 814
Carra Avatar asked Feb 10 '11 16:02

Carra


2 Answers

Yep. Get rid of the { add; remove; } part and the backing delegate field and you're golden:

public event EventHandler UpdateErrorIcons;

That's it!

Let me just add that before you asked this question, I hadn't even thought about the fact that the auto-implemented version of events is inconsistent with that of properties. Personally, I would actually prefer it if auto-implemented events worked the way you first attempted in your question. It would be more consistent, and it would also serve as a mental reminder that events are not identical to delegate fields, just like properties are not identical to regular fields.

Honestly, I think you're the rare exception where you actually knew about the custom syntax first. A lot of .NET developers have no clue there's an option to implement your own add and remove methods at all.


Update: Just for your own peace of mind, I have confirmed using Reflector that the default implementation of events in C# 4 (i.e., the implementation that gets generated when you go the auto-implemented route) is equivalent to this:

private EventHandler _updateErrorIcons;
public event EventHandler UpdateErrorIcons
{
    add
    {
        EventHandler current, original;
        do
        {
            original = _updateErrorIcons;
            EventHandler updated = (EventHandler)Delegate.Combine(original, value);
            current = Interlocked.CompareExchange(ref _updateErrorIcons, updated, original);
        }
        while (current != original);
    }
    remove
    {
        // Same deal, only with Delegate.Remove instead of Delegate.Combine.
    }
}

Note that the above utilizes lock-free synchronization to effectively serialize add and remove calls. So if you're using the latest C# compiler, you don't need to implement add/remove yourself even for synchronization.

like image 129
Dan Tao Avatar answered Oct 26 '22 15:10

Dan Tao


public event EventHandler UpdateErrorIcons; 

is just fine

you can use

yourObbject.UpdateErrorIcons += YourFunction;
like image 26
Stecya Avatar answered Oct 26 '22 16:10

Stecya