[Mono-list] Problem with Events

Jackson Harper jackson at ximian.com
Thu Aug 4 04:56:52 EDT 2005


On Thu, 2005-08-04 at 17:30 +1000, mono-list.1.tracyanne at spamgourmet.com
wrote:
> Can anyone see anything wrong with this code. It looks to me to be
> correct syntax for defining and raising an event. It compiles without
> error, but when I run it I get the following error message

Nothing is ever subscribing to your event, so it is null when you are
trying to invoke it. You need something like:

OnInputError += new InputError (ErrorHandlerFunction); somewhere.

A few general style comments:

1. Normally event handler delegates are named <something>Handler. So
your InputError delegate would be named InputErrorHandler.

2. Normally events names don't start with On. So OnInputError would be
InputError.

3. It's common to wrap the instantiation of an event in a protected
method named On<Event Name>. So you would have a method that looks like
this:

protected void OnInputError (InputErrorEventArgs e)
{
        if (InputError != null)
                InputError (this, e);
}


Cheers,
Jackson


> 
> Unhandled Exception: System.NullReferenceException: Object reference not
> set to an instance of an object
> in [0x00001] (at /home/tracy/MonoDevelop/TestEvents/Main.cs:22)
> RaiseAnEvent:Run ()
> in [0x00007] (at /home/tracy/MonoDevelop/TestEvents/Main.cs:11)
> MainClass:Main (System.String[] args)
> 
> I'm using Mono_1.1.8-2.
> 
> // project created on 04/08/2005 at 17:17
> using System;
> 
> class MainClass
> {
> 				
> 	public static void Main(string[] args)
> 	{
> 		RaiseAnEvent RAE = new RaiseAnEvent();
> 		RAE.Run();
> 	}
> }
> 
> class RaiseAnEvent
> {
> 	public delegate void InputError(object sender, InputErrorEventArgs e);
> 	public event InputError OnInputError;
> 	
> 	public void Run()
> 	{
> 		OnInputError(this, new InputErrorEventArgs("DF", "OI"));
> 	}
> 
> }
> 
> 	
> //Class for passing Input Error messages to the application
> class InputErrorEventArgs : EventArgs
> {
> 	private string errorMessage;
> 	private string errorSource;
> 	
> 	public string ErrorMessage
> 	{
> 		get
> 		{
> 			return errorMessage;
> 		}
> 	}
> 	
> 	public string ErrorSource
> 	{
> 		get
> 		{
> 			return errorSource;
> 		}
> 	}
> 	
> 	public InputErrorEventArgs(string Message, string Source) : base()
> 	{
> 		errorMessage = Message;
> 		errorSource = Source;
> 	}
> }
> _______________________________________________
> Mono-list maillist  -  Mono-list at lists.ximian.com
> http://lists.ximian.com/mailman/listinfo/mono-list



More information about the Mono-list mailing list