tired of checking for null values from event variables?
VB.NET:
If Save IsNot Nothing Then RaiseEvent Save(sender, e)
C#:
if (Save == null) Save(sender, e);
/* you want to raise an event and if the event is not hooked by your usercontrol's users, you want the program to handle it gracefully (no annoying NullReferenceException error messages), here's how: */
public partial class FormRefenceTemplate : Form
{
/*
public delegate void SaveEventHandler(object sender, EventArgs e);
public event SaveEventHandler Save;
*/
// public delegate void TaskEventHandler(object sender, EventArgs e);
// public event TaskEventHandler Save, Open, LoadAll, UndoAll, Print, Help;
/* the following is way much better, we don't want to create our own handler (the commented TaskEventHandler) since there is no need for us to pass/receive additional information(read: custom EventArgs) from the events, just use the default EventArgs */
public event EventHandler Save = notImplemented, LoadAll = notImplemented, UndoAll = notImplemented, Print = notImplemented, Help = notImplemented;
static EventHandler notImplemented = delegate(object sender, EventArgs e)
{
MessageBox.Show("Not yet implemented", "", MessageBoxButtons.OK, MessageBoxIcon.Stop);
};
private void cmdSave_Click(object sender, EventArgs e)
{
// if (sender != null) // no need for this line or in putong-wa: "bu yong" :)
Save(sender, e);
}
}
--------
that's it, just point the event variable to a static delegate
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment