views:

104

answers:

1

Are there any reason why you should not declare an event backing field protected? For example to prevent having to create OnSomeEvent methods for all your events. For example like this:

    protected SomeEventHandler someEvent;

    readonly object someEventLock = new object();

    public event SomeEventHandler SomeEvent
    {
        add
        {
            lock (someEventLock)
                someEvent += value;
        }
        remove
        {
            lock (someEventLock)
                someEvent -= value;
        }
    }

Of course the decending classes would have to remember to lock when raising the event, etc., but anyways.

Any reasons why this should not be done?

+6  A: 

Encapsulation. It's exactly the point you make about subclasses having to remember to lock - which means exposing the lock field as well, etc. That's implementation detail which should be encapsulated by the class.

Creating an OnSomeEvent method means that subclasses don't need to know the details of how you're dealing with the event - they just have a way of raising it. This also reduces code duplication: there's one way of raising the event, rather than having that code all over the place.

I prefer all my fields to be private, unless they're public static readonly fields of immutable types (like string.Empty) - and even then I tend to prefer properties.

Jon Skeet
I see your point. Bad idea it is. =)
Svish