Use of the event keyword in c# -


i wondering exact use of events in c#. still in process of learning c# maybe missing possible use delegates.
in example wrote class method counts 0 2^64 , every time reaches multiple of thousand raises event. here code:

namespace eventdelegate { class program {     static void main(string[] args)     {         eventraiserclass _eventraiser = new eventraiserclass();         _eventraiser.handler = someeventhandler;         _eventraiser.handler += anothereventhandler;         _eventraiser.loop();         console.read();     }      static void someeventhandler(object sender, eventargs args)     {         console.writeline("event raised");     }      static void anothereventhandler(object sendr, eventargs args)     {         console.writeline("event raised (another handler)");     } }  public delegate void handler(object sender, eventargs args);  class eventraiserclass {     public handler handler;     public void loop()     {         (long = 0; < int64.maxvalue; i++)         {             if ((i % 1000) == 0)             {                 eventargs args = new eventargs();                 raiseevent(args);                 system.threading.thread.sleep(1000);             }         }     }      private void raiseevent(eventargs args)     {         if (handler != null)             handler(this, args);     } } 

}

what difference have been if had declared handler delegate variable event public event handler handler.
sorry if been bit vague or missing obvious, wondering if else happens behind scenes when using event rather using delegates or if it's readability purposes.

events , delegates similar, events more restricted, reasons.

in code, kinds of things _eventraiser.handler outside. aren't supposed of things though.

consider line:

_eventraiser.handler = someeventhandler; 

if use delegates, have check every time try attach event handler if delegate null, , initialize =, , if not null, have add handlers +=. if forget initialization, null reference exception, if put in 1 many, overwrite previous things.

if use events instead of delegates in example, don't have of this, and, in fact, can't it. delegates take , pass around other classes, potentially dangerous.

the same goes invoke, , other things can delegate: aren't there events. things can event outside class += , -=, that's it. can view them delegates special public interface complicated getters , setters.

(events have special add , remove syntax, that's rather uncommonly used feature)


Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -