<?xml version="1.0"?>
<rss version="2.0">
	<channel>
		<title>Delegates/Events questions</title>
		<link>http://www.allegro.cc/forums/view/616635</link>
		<description>Allegro.cc Forum Thread</description>
		<webMaster>matthew@allegro.cc (Matthew Leverton)</webMaster>
		<lastBuildDate>Thu, 08 Dec 2016 02:50:11 +0000</lastBuildDate>
	</channel>
	<item>
		<description><![CDATA[<div class="mockup v2"><p>Hello guys, I&#39;ve started teaching myself C#, and am struggling to get my head around some code, specifically relating to delegates/events, and am looking for some advice on if I&#39;m understanding them...</p><p>So I have this line:</p><div class="source-code snippet"><div class="inner"><pre><span class="k1">public</span> delegate <span class="k1">void</span> myEventHandler<span class="k2">(</span>object source, myEventArgs e<span class="k2">)</span><span class="k2">;</span>
</pre></div></div><p>

Which I understand defines the shape of a method, that can be used as a pointer to a function. I also understand the myEventArgs part, so wont type that out!</p><p>Then, later in the code, I have a class that has this code:</p><div class="source-code snippet"><div class="inner"><pre><span class="k1">class</span> myClass
<span class="k2">{</span>
...
<span class="k1">public</span> event myEventHandler onGetString<span class="k2">;</span>
...
<span class="k1">public</span> <span class="k1">void</span> receiveString<span class="k2">(</span>string aString<span class="k2">)</span>
<span class="k2">{</span>
     onGetString<span class="k2">(</span><span class="k1">this</span>, <span class="k1">new</span> myEventArgs<span class="k2">(</span>aString<span class="k2">)</span><span class="k2">)</span><span class="k2">;</span>
<span class="k2">}</span>
...
</pre></div></div><p>

Now, I understand this as saying whenever the receiveString functon is called, it will fire the onGetString event (where some stuff happens in myEventArgs class).</p><p>HOWEVER....this is where my brain stops working....so, in my main class, I have this code:</p><div class="source-code snippet"><div class="inner"><pre>myClass myClassInstance <span class="k3">=</span> <span class="k1">new</span> myClass<span class="k2">(</span><span class="k2">)</span><span class="k2">;</span>

myClassInstance.onGetString <span class="k3">+</span><span class="k3">=</span> <span class="k1">new</span> myEventHandler<span class="k2">(</span>dealWithString<span class="k2">)</span><span class="k2">;</span>

<span class="k1">public</span> <span class="k1">void</span> dealWithString<span class="k2">(</span>object source, myEventArgs e<span class="k2">)</span>
<span class="k2">{</span>
     printString<span class="k2">(</span>e.getString<span class="k2">(</span><span class="k2">)</span><span class="k2">)</span><span class="k2">;</span>
<span class="k2">}</span>
</pre></div></div><p>

NOW, my problem is this; does that mean that, whenever myClass calls onGetString (when onReceiveString is called), it will also call dealWithString in the main class? I hope that makes sense? I didn&#39;t write this code, I&#39;m just trying to understand it!! Does it mean I can basically use += to keep adding custom methods on top of onGetString? So whenever onGetString gets called in myClass, all other classes that have added using += will also get their attached method called? Am I making ANY sense??
</p></div>]]>
		</description>
		<author>no-reply@allegro.cc (Dizzy Egg)</author>
		<pubDate>Wed, 07 Dec 2016 20:45:24 +0000</pubDate>
	</item>
	<item>
		<description><![CDATA[<div class="mockup v2"><p>The &#39;event&#39; keyword is some magic that&#39;s worth describing separately. A field marked as &#39;event&#39; will allow <i>only</i> += and -= operations from any location outside the class (i.e. calling it or otherwise taking its value will fail as if the field is declared private). I&#39;m not sure if operations like directly assigning it are allowed inside the class. You can also declare explicit &#39;add&#39; and &#39;remove&#39; handlers (much like &#39;get&#39; and &#39;set&#39; for properties) if you want to.</p><p>There are two things to explain with &quot;new myEventHandler(dealWithString)&quot;:
</p><ol><li><p>You can actually just write &quot;dealWithString&quot;, and the &quot;new myEventHandler(...)&quot; part will be generated for you.
</p></li><li><p>Either way, you are capturing the &#39;this&#39; pointer at the time (it is part of the delegate instance you just made), so yes, it will be called on your main class instance later on.</p></li></ol><p>The next two things you might find interesting:</p><p>Lambda functions are like inline delegates, but these are capable of capturing local variables in addition to &#39;this&#39;. So you can write something like:<br /><span class="source-code">myClassInstance.onGetString <span class="k3">+</span><span class="k3">=</span> <span class="k2">(</span>source, e<span class="k2">)</span> <span class="k3">=</span><span class="k3">&gt;</span> <span class="k2">{</span> ...code goes here... <span class="k2">}</span><span class="k2">;</span></span><br />(You can write explicit parameter types too if you want to.) Be aware that if you do this, the relevant locals get compiled as references into a temporary object instantiated each time their scope is entered (this is true both inside and outside the lambda). [EDIT: Also, beware of the lambda foreach bug - the &#39;foreach&#39; iterator variable is instantiated once, so if you use it in a lambda inside the loop, then all instances of the lambda ultimately see the last value it took on during the iteration. However, they fixed this in some new version of C# by changing the way &#39;foreach&#39; is compiled.]</p><p>If you choose not to use &#39;event&#39;, then the code will still work but through a different mechanism. The operators &#39;+&#39; and &#39;-&#39; are supported for delegates, but they create new instances, just as with strings. So, if you write &quot;x += y&quot;, then it compiles into a read operation on &#39;x&#39;, a combine operation which makes a new delegate object without disturbing the old ones, and then an assignment operation (just as with strings). A delegate contains a list of methods, which is used if you later use the &#39;-&#39; or &#39;-=&#39; operators. Calling a delegate entails calling the methods in sequence. Perhaps an event field is implemented this way too, but in a more wrapped fashion (the class does it itself), I&#39;m not sure - and of course you have the option to override this, which you don&#39;t if you don&#39;t use the &#39;event&#39; keyword.</p><p>Hope that helps <img src="http://www.allegro.cc/forums/smileys/smiley.gif" alt=":)" />
</p></div>]]>
		</description>
		<author>no-reply@allegro.cc (Bruce Perry)</author>
		<pubDate>Wed, 07 Dec 2016 21:00:40 +0000</pubDate>
	</item>
	<item>
		<description><![CDATA[<div class="mockup v2"><p>Thanks Bruce, some helpful points there. Can you clarify one thing for me, in my example, when <span class="source-code">myClass</span> fires <span class="source-code">onGetString</span>, it sends the received string (via a <span class="source-code"><span class="k1">new</span> myEventArgs</span>), and obviously in the main class, is prints the string sent...SO, does that mean in the main class when <span class="source-code">dealWithString</span> is called, it uses the arguments sent by myClass&#39;s <span class="source-code">onGetString?</span> (ie <span class="source-code"><span class="k1">this</span></span> and <span class="source-code"><span class="k1">new</span> myEventArgs<span class="k2">(</span>aString<span class="k2">)</span></span>)
</p></div>]]>
		</description>
		<author>no-reply@allegro.cc (Dizzy Egg)</author>
		<pubDate>Wed, 07 Dec 2016 21:17:49 +0000</pubDate>
	</item>
	<item>
		<description><![CDATA[<div class="mockup v2"><p>Yep. That part of the operation is exactly like a function pointer call <img src="http://www.allegro.cc/forums/smileys/smiley.gif" alt=":)" /></p><p>Or if you want a C++ parallel, then a functor - one which wraps the &#39;this&#39; and any locals, same way a C++ functor (callable object) can.
</p></div>]]>
		</description>
		<author>no-reply@allegro.cc (Bruce Perry)</author>
		<pubDate>Wed, 07 Dec 2016 21:34:43 +0000</pubDate>
	</item>
	<item>
		<description><![CDATA[<div class="mockup v2"><p>That&#39;s awesome thank you for helping Bruce.
</p></div>]]>
		</description>
		<author>no-reply@allegro.cc (Dizzy Egg)</author>
		<pubDate>Wed, 07 Dec 2016 21:43:34 +0000</pubDate>
	</item>
	<item>
		<description><![CDATA[<div class="mockup v2"><p>The usual pattern is as follows (note, C# usually uses upper-camel-case, not lower-camel-case as a style rule):</p><div class="source-code"><div class="toolbar"><span class="button numbers"><b>#</b></span><span class="button select">Select</span><span class="button expand">Expand</span></div><div class="inner"><span class="number">  1</span><span class="k1">using</span> System<span class="k2">;</span>
<span class="number">  2</span>
<span class="number">  3</span><span class="k1">public</span> <span class="k1">class</span> Program
<span class="number">  4</span><span class="k2">{</span>
<span class="number">  5</span>    <span class="k1">public</span> <span class="k1">static</span> <span class="k1">int</span> Main<span class="k2">(</span>string<span class="k2">[</span><span class="k2">]</span> argv<span class="k2">)</span>
<span class="number">  6</span>    <span class="k2">{</span>
<span class="number">  7</span>        var foo <span class="k3">=</span> <span class="k1">new</span> Foo<span class="k2">(</span><span class="k2">)</span><span class="k2">;</span>
<span class="number">  8</span>
<div class="highlight"><span class="number">  9</span>        foo.Over9000 <span class="k3">+</span><span class="k3">=</span> <span class="k2">(</span>sender, args<span class="k2">)</span> <span class="k3">=</span><span class="k3">&gt;</span> <span class="k2">{</span> </div><span class="number"> 10</span>            Console.WriteLine<span class="k2">(</span><span class="s">"Wow, we've counted to {0}!"</span>, args.Count<span class="k2">)</span><span class="k2">;</span> 
<span class="number"> 11</span>        <span class="k2">}</span><span class="k2">;</span> 
<span class="number"> 12</span>
<span class="number"> 13</span>        <span class="k1">for</span><span class="k2">(</span><span class="k1">int</span> i<span class="k3">=</span><span class="n">0</span>,l<span class="k3">=</span><span class="n">9010</span><span class="k2">;</span> i<span class="k3">&lt;</span>l<span class="k2">;</span> i<span class="k3">+</span><span class="k3">+</span><span class="k2">)</span>
<span class="number"> 14</span>        <span class="k2">{</span>
<span class="number"> 15</span>            foo.Increment<span class="k2">(</span><span class="k2">)</span><span class="k2">;</span>
<span class="number"> 16</span>        <span class="k2">}</span>
<span class="number"> 17</span>
<span class="number"> 18</span>        <span class="k1">return</span> <span class="n">0</span><span class="k2">;</span>
<span class="number"> 19</span>    <span class="k2">}</span>
<span class="number"> 20</span><span class="k2">}</span>
<span class="number"> 21</span>
<span class="number"> 22</span><span class="k1">public</span> <span class="k1">class</span> Foo
<span class="number"> 23</span><span class="k2">{</span>
<span class="number"> 24</span>    <span class="c">// Define your event as an EventHandler, either with type argument</span>
<span class="number"> 25</span>    <span class="c">// or implicitly using EventArgs.</span>
<span class="number"> 26</span>    <span class="k1">public</span> event EventHandler<span class="k3">&lt;</span>Over9000EventArgs&gt; Over9000<span class="k2">;</span> 
<span class="number"> 27</span>
<span class="number"> 28</span>    <span class="k1">public</span> <span class="k1">int</span> Count <span class="k2">{</span> get<span class="k2">;</span> <span class="k1">protected</span> set<span class="k2">;</span> <span class="k2">}</span>
<span class="number"> 29</span>
<span class="number"> 30</span>    <span class="k1">public</span> <span class="k1">void</span> Increment<span class="k2">(</span><span class="k2">)</span>
<span class="number"> 31</span>    <span class="k2">{</span>
<span class="number"> 32</span>        <span class="k1">if</span><span class="k2">(</span><span class="k3">+</span><span class="k3">+</span>this.Count <span class="k3">&gt;</span> <span class="n">9000</span><span class="k2">)</span>
<span class="number"> 33</span>        <span class="k2">{</span>
<span class="number"> 34</span>            <span class="c">// When the event occurs you trigger handlers, usually using a</span>
<span class="number"> 35</span>            <span class="c">// wrapper like this.</span>
<div class="highlight"><span class="number"> 36</span>            this.OnOver9000<span class="k2">(</span>this.Count<span class="k2">)</span><span class="k2">;</span> </div><span class="number"> 37</span>        <span class="k2">}</span>
<span class="number"> 38</span>    <span class="k2">}</span>
<span class="number"> 39</span>
<span class="number"> 40</span>    <span class="c">// To avoid duplicating code you usually define a wrapper to trigger the</span>
<span class="number"> 41</span>    <span class="c">// event handlers.</span>
<span class="number"> 42</span>    <span class="k1">protected</span> <span class="k1">void</span> OnOver9000<span class="k2">(</span>Over9000EventArgs args<span class="k2">)</span>
<span class="number"> 43</span>    <span class="k2">{</span>
<div class="highlight"><span class="number"> 44</span>        <span class="k1">if</span><span class="k2">(</span>this.Over9000 <span class="k3">!</span><span class="k3">=</span> null<span class="k2">)</span> </div><span class="number"> 45</span>        <span class="k2">{</span>
<div class="highlight"><span class="number"> 46</span>            this.Over9000<span class="k2">(</span><span class="k1">this</span>, args<span class="k2">)</span><span class="k2">;</span> </div><span class="number"> 47</span>        <span class="k2">}</span>
<span class="number"> 48</span>    <span class="k2">}</span>
<span class="number"> 49</span>
<span class="number"> 50</span>    <span class="c">// Often I'll wrap the constructor of the event args type so that the</span>
<span class="number"> 51</span>    <span class="c">// caller doesn't have to construct the args object itself.</span>
<span class="number"> 52</span>    <span class="k1">protected</span> <span class="k1">void</span> OnOver9000<span class="k2">(</span><span class="k1">int</span> count<span class="k2">)</span>
<span class="number"> 53</span>    <span class="k2">{</span>
<div class="highlight"><span class="number"> 54</span>        this.OnOver9000<span class="k2">(</span><span class="k1">new</span> Over9000EventArgs<span class="k2">(</span>count<span class="k2">)</span><span class="k2">)</span><span class="k2">;</span> </div><span class="number"> 55</span>    <span class="k2">}</span>
<span class="number"> 56</span><span class="k2">}</span>
<span class="number"> 57</span>
<span class="number"> 58</span><span class="c">// Derive from EventArgs base class if your event has state, otherwise</span>
<span class="number"> 59</span><span class="c">// just use the base.</span>
<div class="highlight"><span class="number"> 60</span><span class="k1">public</span> <span class="k1">class</span> Over9000EventArgs: </div><span class="number"> 61</span>    EventArgs
<span class="number"> 62</span><span class="k2">{</span>
<span class="number"> 63</span>    <span class="k1">public</span> Over9000EventArgs<span class="k2">(</span><span class="k1">int</span> count<span class="k2">)</span> <span class="k2">{</span> this.Count <span class="k3">=</span> count<span class="k2">;</span> <span class="k2">}</span>
<span class="number"> 64</span>
<span class="number"> 65</span>    <span class="k1">public</span> <span class="k1">int</span> Count <span class="k2">{</span> get<span class="k2">;</span> <span class="k1">protected</span> set<span class="k2">;</span> <span class="k2">}</span>
<span class="number"> 66</span><span class="k2">}</span>
</div></div><p>

Output:</p><pre class="terminal">Wow, we&#39;ve counted to 9001!
Wow, we&#39;ve counted to 9002!
Wow, we&#39;ve counted to 9003!
Wow, we&#39;ve counted to 9004!
Wow, we&#39;ve counted to 9005!
Wow, we&#39;ve counted to 9006!
Wow, we&#39;ve counted to 9007!
Wow, we&#39;ve counted to 9008!
Wow, we&#39;ve counted to 9009!
Wow, we&#39;ve counted to 9010!</pre><p>
</p></div>]]>
		</description>
		<author>no-reply@allegro.cc (bamccaig)</author>
		<pubDate>Wed, 07 Dec 2016 23:06:47 +0000</pubDate>
	</item>
	<item>
		<description><![CDATA[<div class="mockup v2"><p>I believe the newest C# lets you replace this:
</p><div class="source-code snippet"><div class="inner"><pre><span class="k1">if</span><span class="k2">(</span>this.Over9000 <span class="k3">!</span><span class="k3">=</span> null<span class="k2">)</span> 
<span class="k2">{</span>
    this.Over9000<span class="k2">(</span><span class="k1">this</span>, args<span class="k2">)</span><span class="k2">;</span> 
<span class="k2">}</span>
</pre></div></div><p>
with this:</p><p><span class="source-code">this.Over9000?<span class="k2">(</span><span class="k1">this</span>, args<span class="k2">)</span><span class="k2">;</span></span>
</p></div>]]>
		</description>
		<author>no-reply@allegro.cc (Bruce Perry)</author>
		<pubDate>Thu, 08 Dec 2016 00:12:05 +0000</pubDate>
	</item>
	<item>
		<description><![CDATA[<div class="mockup v2"><p>Ah, that&#39;s cool. I knew they were introducing a null-safe dot operator. Either &quot;?.&quot; or &quot;.?&quot;. I forget. I haven&#39;t gotten to use those features yet because we weren&#39;t getting Visual Studio upgrades... Though now I think that we&#39;re all running the free community edition so we probably could take advantage of those features now. C# events happen to come up relatively rarely in my professional work because it&#39;s almost all Web-based.
</p></div>]]>
		</description>
		<author>no-reply@allegro.cc (bamccaig)</author>
		<pubDate>Thu, 08 Dec 2016 00:48:22 +0000</pubDate>
	</item>
	<item>
		<description><![CDATA[<div class="mockup v2"><p>Hello bam - couple of questions, 1) why do you use 2 versions of <span class="source-code"><span class="k1">void</span> OnOver9000</span>? One with EventArgs and one with an <span class="source-code"><span class="k1">int</span></span>? 2) why do you not use a delegate? 3) Why doesn&#39;t your definition of void OnOver9000 have an object as an argument, yet your call to += does?
</p></div>]]>
		</description>
		<author>no-reply@allegro.cc (Dizzy Egg)</author>
		<pubDate>Thu, 08 Dec 2016 02:27:29 +0000</pubDate>
	</item>
	<item>
		<description><![CDATA[<div class="mockup v2"><div class="quote_container"><div class="title"><a href="https://www.allegro.cc/forums/thread/616635/1026847#target">Dizzy Egg</a> said:</div><div class="quote"><p>
Hello bam - couple of questions, 1) why do you use 2 versions of <span class="source-code"><span class="k1">void</span> OnOver9000</span>? One with EventArgs and one with an <span class="source-code"><span class="k1">int</span></span>? 2) why do you not use a delegate? 3) Why doesn&#39;t your definition of void OnOver9000 have an object as an argument, yet your call to += does?
</p></div></div><p>

1) The OnOver9000 overload is an optional convenience. If it so happens that the event can occur in many places. Putting this into a method saves the redundant task of constructing the object with the integer parameter.</p><p>On the other hand, having both makes it trivial and efficient to pass an existing Over9000EventArgs instance as the argument rather than forcing yourself to construct a new one just because your API is limited. The int-overload&#39;s job is just constructing the args object and passing it on to the other one that actually does the work.</p><p>2) I am using delegates, but it&#39;s being hidden with syntactic-sugar and API-sugar. The standard <a href="https://msdn.microsoft.com/en-us/library/db0etb8x(v=vs.110).aspx">EventHandler&lt;T&gt;</a> type <i>is</i> a delegate. This is a generic definition for the shape of an event. This saves you the redundant job of defining a delegate type for each event.</p><div class="source-code snippet"><div class="inner"><pre>EventHandler<span class="k3">&lt;</span>X&gt;
<span class="c">// is the same as</span>
XEventHandler
<span class="c">// where</span>
delegate <span class="k1">void</span> EventHandler<span class="k3">&lt;</span>T&gt;<span class="k2">(</span>object sender, T args<span class="k2">)</span><span class="k2">;</span>
delegate <span class="k1">void</span> XEventHandler<span class="k2">(</span>object sender, X args<span class="k2">)</span><span class="k2">;</span>
</pre></div></div><p>

There is an additional version too for when your event takes no real arguments:</p><div class="source-code snippet"><div class="inner"><pre>delegate <span class="k1">void</span> EventHandler<span class="k2">(</span>object sender, EventArgs args<span class="k2">)</span><span class="k2">;</span>
</pre></div></div><p>

It just accepts the stateless base class to fit the event interface pattern.</p><p>3) There are two OnOver9000 methods. One accepts an int, the other accepts the derived EventArgs object. The int override constructs the derived object from the int parameter and passes that along to the object override. The object override actually invokes the delegate with the EventArgs parameter. It&#39;s just a bit of forward-thinking code-reuse. Completely optional and not at all necessary here.
</p></div>]]>
		</description>
		<author>no-reply@allegro.cc (bamccaig)</author>
		<pubDate>Thu, 08 Dec 2016 02:42:26 +0000</pubDate>
	</item>
	<item>
		<description><![CDATA[<div class="mockup v2"><p>Excellent, thanks bam. I like the overloaded function creating the EventArgs, that&#39;s very handy!
</p></div>]]>
		</description>
		<author>no-reply@allegro.cc (Dizzy Egg)</author>
		<pubDate>Thu, 08 Dec 2016 02:50:11 +0000</pubDate>
	</item>
</rss>
