using a delegate to handle events within an interface, C# -


i trying study mta98-731 c# beginner. not figure out solution following question, can me? thanks;

imagine writing code creating , handling events in program. class sampleclass needs implement following interface:

public delegate void sampledelegate(); public interface isampleevents { event sampledelegate sampleevent; void invoke(); } 

you need write code sampleclass , test method creates instance of sampleclass , invokes event. code should write?

i have written following:

public class sampleclass:isampleevents {     public sampleclass()     {         sampleevent = new sampledelegate(invoke);      }      //public event sampledelegate sampleevent ;      public void invoke()     {         system.console.writeline("invoke");     }       public event sampledelegate sampleevent; }   class program {      static void main(string[] args)     {                   sampleclass s = new sampleclass();       } } 

but not seem invoke invoke() function. can help? clueless :(

here code raising event:

public class sampleclass : isampleevents {     public event sampledelegate sampleevent; // declare event      public void invoke()     {         if (sampleevent != null) // check if handlers attached            sampleevent(); // raise event (i.e. invoke event delegate)     } } 

don't forget check if there existing subscribers event before raising it. usage of sample class:

class program {         static void main(string[] args)     {         sampleclass s = new sampleclass(); // create instance of class event         s.sampleevent += sampleeventhandler; // subscribe event         s.invoke(); // invoke logic raises event     }      private static void sampleeventhandler()     {         console.writeline("invoked"); // handle event     } } 

when adding event handler can use method name

s.sampleevent += sampleeventhandler; 

which syntax sugar creating new delegate:

s.sampleevent += new sampledelegate(sampleeventhandler); 

Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -