Raising a base class event

S

Simon

Hi folks,

I have an object library where there are base classes that have a
declared event. I have hit the problem where the derived class cannot
raise the event. After some thought I had the idea of declaring a
protected method in the base class to raise the event, so that the
derived class can just call this method when it needs to raise this event.

Is this good form, or is there a better way.

eg

public class myBaseClass {

public delegate void ChangedDelegate();
public event ChangedDelegate OnChanged;

protected void RaiseChangedEvent() {
if (OnChanged != null)
OnChanged();
}
}

public class myDerivedClass : myBaseClass {

private string _someValue;

public string SomeValue {
get { return _someValue; }
set {
if (_someValue != value)
RaiseChangedEvent();
_someValue = value;
}
}
 
D

Daniel O'Connell [C# MVP]

Simon said:
Hi folks,

I have an object library where there are base classes that have a declared
event. I have hit the problem where the derived class cannot raise the
event. After some thought I had the idea of declaring a protected method
in the base class to raise the event, so that the derived class can just
call this method when it needs to raise this event.

Is this good form, or is there a better way.

That is about the only way available. Its just fine
 
?

=?iso-8859-1?Q?Anders=20Nor=e5s?=

Your code is good, but there is one little detail that should be changed.
In the section:
set {
if (_someValue != value)
RaiseChangedEvent();
_someValue = value;
}
}
....you're rasing the changed event before the value is changed. The _someValue
member should be set first, and then ypu should call the RaiseChangedEvent
method. After all, the value hasn't changed until you assign a new value
to it.

Anders Norås
http://dotnetjunkies.com/weblog/anoras/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top