C# Event Handlers Using an Enum
Posted
by Jimbo
on Stack Overflow
See other posts from Stack Overflow
or by Jimbo
Published on 2010-04-05T13:34:59Z
Indexed on
2010/04/05
13:43 UTC
Read the original article
Hit count: 254
I have a StatusChanged event that is raised by my object when its status changes - however, the application needs to carry out additional actions based on what the new status is.
e.g If the new status is Disconnected, then it must update the status bar text and send an email notification.
So, I wanted to create an Enum with the possible statuses (Connected, Disconnected, ReceivingData, SendingData etc.) and have that sent with the EventArgs parameter of the event when it is raised (see below)
Define the object:
class ModemComm
{
public event CommanderEventHandler ModemCommEvent;
public delegate void CommanderEventHandler(object source, ModemCommEventArgs e);
public void Connect()
{
ModemCommEvent(this, new ModemCommEventArgs ModemCommEventArgs.eModemCommEvent.Connected));
}
}
Define the new EventArgs parameter:
public class ModemCommEventArgs : EventArgs{
public enum eModemCommEvent
{
Idle,
Connected,
Disconnected,
SendingData,
ReceivingData
}
public eModemCommEvent eventType { get; set; }
public string eventMessage { get; set; }
public ModemCommEventArgs(eModemCommEvent eventType, string eventMessage)
{
this.eventMessage = eventMessage;
this.eventType = eventType;
}
}
I then create a handler for the event in the application:
ModemComm comm = new ModemComm();
comm.ModemCommEvent += OnModemCommEvent;
and
private void OnModemCommEvent(object source, ModemCommEventArgs e)
{
}
The problem is, I get a 'Object reference not set to an instance of an object' error when the object attempts to raise the event. Hoping someone can explain in n00b terms why and how to fix it :)
© Stack Overflow or respective owner