Connecting Tech Pros Worldwide Forums | Help | Site Map

EventHandler in C#

Newbie
 
Join Date: May 2008
Posts: 24
#1: Sep 3 '08
Dear Friends.

here is my code :

Expand|Select|Wrap|Line Numbers
  1. class test
  2. {
  3.     public event EventHandler RequestStart;
  4.     public event EventHandler RequestFailed;
  5.  
  6.     public void Start(){
  7.       RequestStart("string" , new EventArgs());
  8.       return ; 
  9.     }
  10. }
  11.  
  12. class app
  13. {
  14.  
  15.   public app(){
  16.    test _t = new test();
  17.    _t.RequestFailed += new EventHandler(fa);
  18.    _t.Start();
  19.    } 
  20.  
  21.     void fa(object sender, EventArgs e){}
  22. }

I have a "Object reference not set to an instance of an object." exception in line : 7
What is problem ?


Thank you .
Ali.MZ

Plater's Avatar
Moderator
 
Join Date: Apr 2007
Location: New England
Posts: 7,161
#2: Sep 3 '08

re: EventHandler in C#


You did not assign a handler to RequestStart, but are trying to use it.
Newbie
 
Join Date: May 2008
Posts: 24
#3: Sep 3 '08

re: EventHandler in C#


solution:
Expand|Select|Wrap|Line Numbers
  1. class test
  2. {
  3.     public event EventHandler RequestStart;
  4.     public event EventHandler RequestFailed;
  5.  
  6.  protected virtual void OnRequestStart(...........)
  7.         {
  8.             if (RequestStart != null) RequestStart(........);
  9.         }
  10.     public void Start(){
  11.       OnRequestStart("string" , new EventArgs());
  12.       return ; 
  13.     }
  14. }
  15.  
  16. class app
  17. {
  18.  
  19.   public app(){
  20.    test _t = new test();
  21.    _t.RequestFailed += new EventHandler(fa);
  22.    _t.Start();
  23.    } 
  24.  
  25.     void fa(object sender, EventArgs e){}
  26. }
Reply