Delegate problem

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello,

I want to execute a delegate (event) in tha base class from a derived class
but i get comile time error. Is there a work arround?

base class :

public abstract class Document
{
public event EventHandler OnDataChanged;

public virtual void SetData(string xmlString)
{
_data = xmlString;
this.IsDirty = true;
if (OnDataChanged != null)
{
OnDataChanged(this, new EventArgs());
}
}


derived class :

public class RuleXmlDocument : Document
{
void RaiseMyEvent(object sender, EventArgs e)
{
if (OnDataChanged != null)
{
OnDataChanged(sender, e);
}
}

----------------------------------------------------------------
Here what i want is when i call RaiseMyEvent() function the event should be
raised but. Its a compile time error. Some how base class delegate is
publically available but cannot be used as its used in the base class.

Any Guesses?

Thanx in advance

Ayyaz-
 
A child class cannot raise an event designed in the ancestor class.

What you should do is define a method called RaiseOnDataChanged or something
that is protected. Then, you can call this method from the child class (or
even the ancestor itself, for that matter), and that method will raise the
event.
 
Hi Ayyaz,

The event declaration and invocation standard is to name your event without the "On" prefix and to use a protected method with the
"On" prefix for invocation:

public abstract class Document
{
/// <summary>Event raised when the data has changed.</summary>
public event EventHandler DataChanged;

/// <summary>Raises the <see cref="DataChanged" /> event.</summary>
/// <param name="e">Arguments for the event.</param>
protected virtual void OnDataChanged(EventArgs e)
{
if (DataChanged != null)
DataChanged(this, e);
}
}

public class RuleXmlDocument : Document
{
public void MethodThatChangesData()
{
// TODO: some work on data

// raise the DataChanged event
OnDataChanged(EventArgs.Empty);
}
}


This standard is not thread-safe. For information on thread-safety in event members read this article:

Jon Skeet's article on delegates and events:
http://www.yoda.arachsys.com/csharp/events.html
 
That was an option I had, before posting to this forum but I was not sure if
it is a good practice.

Thanx for the reply,

Ayyaz-
 
Back
Top