Delegate problem

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-
 
M

Marina Levit [MVP]

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.
 
D

Dave Sexton

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
 
G

Guest

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-
 

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