Raising an event in C#

Raising an event in C# is ridiculously complicated, but here goes.  This is based on MSDN “How to:  Implement Events in Your Class”.

ITEM 1
Create a class for the event arguments.
public class FactoryInfoEventArgs : EventArgs
{

private string mSource;
public string Source
{

get { return mSource; }
set { mSource = value; }
}

private string mMessage;
public string Message
{

get { return mMessage; }
set { mMessage = value; }
}

public FactoryInfoEventArgs(string eventSource, string eventMessage)
{

Source = eventSource;
Message = eventMessage;
}
}

ITEM 2

Create a delegate (outside the class).

public delegate void FactoryInfoEventHandler(object sender, FactoryInfoEventArgs e);

 ITEM 3

In the class that is supposed to raise the event, create the event.

public event FactoryInfoEventHandler InfoEvent;

ITEM 4

In the class that raises the event, create a protected void method to raise it.

protected void OnFactoryInfoEvent(string source, string message)
{
FactoryInfoEventArgs e = new FactoryInfoEventArgs(source, message);
FactoryInfoEventHandler handler = InfoEvent;
if (handler != null){ handler(this, e);
}
}

Advertisements

Post a Comment

Required fields are marked *
*
*

%d bloggers like this: