Search code examples
c#eventsautomatic-properties

Can you fire events with automatic properties?


I was wondering if I can use automatic properties and still be able to fire events on property changed. Here are my current classes. (The actual User class got way more properties/fields of course).

public delegate void UserEventHandler(object sender, EventArgs e);

public class User
{
    public event UserEventHandler Changed;

    private string _UserName;
    public string UserName
    {
        get
        {
            return _UserName;
        }
        private set
        {
            _UserName = value;
            this.OnChanged(EventArgs.Empty);
        }
    }

    protected void OnChanged(EventArgs e)
    {
        if (Changed != null)
        {
            Changed(this, e);
        }
    }
}

So I was wondering if there is a way I could take advantage of the automatic properties and still be able to fire the OnChanged events. In other words : Are semi-automatic properties possible?


Solution

  • You can use PostSharp.
    Example