I am using C# 3.0. Following the standard event pattern I have:
public event EventHandler<EventArgs> SomeEventHappens;
protected virtual void OnSomeEventHappens(EventArgs e)
{
if (SomeEventHappens != null)
{
SomeEventHappens(this, e);
}
}
private object _someProperty;
public object SomeProperty
{
get
{
return _someProperty;
}
private set
{
if (_someProperty == value)
{
return;
}
OnSomeEventHappens(EventArgs.Empty);
_someProperty = value;
}
}
Within my same class I would like to take some actions when SomeProperty
changes. The way I see it I have 3 alternatives:
1) Do stuff within my SomeProperty
setter. Something rubs me the wrong way about doing this since I try to subscribe to the philosophy of everything should do one thing and do it well. Cramming stuff into a setter seems to go against that, or at least has the propensity to.
2) Do stuff in OnSomeEventHappens
. Again, seems to go a little against keeping this in simple pieces. Also, if this method gets overridden, could potentially lose functionality if the implementer does not call the base method.
3) Have the class subscribe to SomeEventHappens
. To me this seems to be the proper choice as far as encapsulation is concerned, and seems pretty clean. Again, possible repercussions if OnSomeEventHappens
is overridden.
Maybe there is something more elegant? I cannot decide between option 2 and 3, and I am curious as to what the Best Practice is. Maybe the safest place is in the property setter after all.
Thoughts?
Update: Thanks for the great comments and answers below. I have learned that it is "OK" to have a class subscribe to its own events, although in my case I am leaning to not do due to overhead. I have put thought into the behavior of potential overriders of my virtual methods and what exactly I want to happen.
In my real-world case, I do not really want the events to be raised without the property being set. As the answers below have guided my thought process, I think I may go with option 1, due to the lower overhead, the reduced risk of improper behavior from inheritors, and it just generally makes better sense to me. Thanks again!