i have this code I'm playing around with, but it causes a, for me at least, weird exception.
public class Flight
{
public class MessageEventArgs : System.EventArgs
{
public string msgContent;
}
public event System.EventHandler LogMessage;
public void StartFlight()
{
string tmpDeparture = this.Departure;
string tmpDestination = this.Destination;
this.OnLogUpdate("Taking off from " + tmpDeparture + " now.");
this.Destination = tmpDeparture;
Thread.Sleep(1000);
this.OnLogUpdate("Arriving in " + tmpDestination + " now.");
this.Departure = tmpDestination;
}
protected virtual void OnLogUpdate(string logMessage)
{
MessageEventArgs e = new MessageEventArgs();
if (logMessage == "")
return;
e.msgContent = logMessage;
LogMessage(this, e);
}
}
It causes a NullReferenceException at the, LogMessage(this, e);
I don't understand why it causes said exception when i have a practically identical setup in another class that works fine.
Also, when checking with the variable inspector, both this
and e
is set, and therefor not Null.
I'm still a somewhat new to C#, and especially events and delegates, so i have probably missed something more or less obvious
[Edit]
If it is because the event have no subscriptions, what is wrong with this?
public partial class MainForm : Form
{
Airport airport = new Airport();
Flight flight = new Flight();
public MainForm()
{
InitializeComponent();
InitializeEvents();
}
private void InitializeEvents()
{
this.airport.ErrorMessage += new System.EventHandler(OnErrorReceived);
this.flight.LogMessage += new System.EventHandler(OnLogReceived);
}
the subscription for the airport error message is working fine, but the one for the flight LogMessage doesn't?