{"id":245,"date":"2022-03-19T23:43:12","date_gmt":"2022-03-19T23:43:12","guid":{"rendered":"https:\/\/baldsolutions.com\/?p=245"},"modified":"2022-03-20T20:31:05","modified_gmt":"2022-03-20T20:31:05","slug":"closure-unexpected-exception","status":"publish","type":"post","link":"https:\/\/baldsolutions.com\/index.php\/2022\/03\/19\/closure-unexpected-exception\/","title":{"rendered":"Closure &#8211; unexpected exception"},"content":{"rendered":"\n<h1 class=\"wp-block-heading\">Introduction<\/h1>\n\n\n\n<p>Closure itself isn&#8217;t a brand new topic.  I&#8217;ve seen many blog articles that explain the topic (there&#8217;s even a <a href=\"https:\/\/en.wikipedia.org\/wiki\/Closure_(computer_programming)\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Wikipedia\">Wikipedia<\/a> page in a few languages!), however, I decided to present my own example. To be honest, thanks to this post I finally focused on its internals and what really happens behind the scenes. In this post I&#8217;ll show you a simple example of the closure that might be the root of an exception. <\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Example<\/h1>\n\n\n\n<p>Let&#8217;s consider the following code snippet:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class Closure\n{\n    public static Func&lt;int&gt; GetFuncWithClosure(int arg)\n    {\n        int internalVariable = arg;\n\n        var func = new Func&lt;int&gt;(() =&gt;\n        {\n            internalVariable -= 5;\n\n            return 10 \/ internalVariable;\n        });\n\n        return func;\n    }\n\n    public static Func&lt;int, int&gt; GetFuncWithoutClosure()\n    {\n        var func = new Func&lt;int, int&gt;((arg) =&gt;\n        {\n            arg -= 5;\n\n            return 10 \/ arg;\n        });\n\n        return func;\n    }\n}<\/code><\/pre>\n\n\n\n<p>As you can see there&#8217;s one simple class named <code>Closure<\/code> and two static methods named <code>GetFuncWithClosure<\/code> and <code>GetFuncWithoutClosure<\/code>. First method returns the Func&lt;int&gt; &#8211; in other words, a function that accepts no argument and returns an integer. Second method returns the Func&lt;int, int&gt; &#8211; a function that accepts one argument and returns an integer.  There&#8217;s one caveat in terms of <code>GetFuncWithClosure<\/code> though, returned function uses the variable named <code>internalVariable<\/code>, hence closure.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Tests<\/h1>\n\n\n\n<p>Having our program ready to go, let&#8217;s focus on a few unit tests.<\/p>\n\n\n\n<pre class=\"wp-block-code\" style=\"font-size:14px\"><code>&#91;Fact]\npublic void GetFuncWithClosure_InvokeOnce_GetExpectedResult()\n{\n    \/\/arrange\n    var func = Closure.GetFuncWithClosure(10);\n\n    \/\/act\n    var result = func();\n\n    \/\/assert\n    Assert.Equal(2, result);\n}\n\n&#91;Fact]\npublic void GetFuncWithClosure_InvokeMoreThanOnce_GetUnexpectedResult()\n{\n    \/\/arrange\n    var func = Closure.GetFuncWithClosure(10);\n\n    \/\/act &amp; assert\n    var result = func();\n    Assert.Equal(2, result);\n\n    Assert.Throws&lt;DivideByZeroException>(() => func());\n}\n\n&#91;Fact]\npublic void GetFuncWithoutClosure_InvokeOnce_GetExpectedResult()\n{\n    \/\/arrange\n    var func = Closure.GetFuncWithoutClosure();\n\n    \/\/act\n    var result = func(10);\n\n    \/\/assert\n    Assert.Equal(2, result);\n}\n\n&#91;Fact]\npublic void GetFuncWithoutClosure_InvokeMoreThanOnce_GetExpectedResult()\n{\n    \/\/arrange\n    var func = Closure.GetFuncWithoutClosure();\n\n    \/\/act\n    var result = func(10);\n    var result2 = func(10);\n    \n    \/\/assert\n    Assert.Equal(2, result);\n    Assert.Equal(2, result2);\n}<\/code><\/pre>\n\n\n\n<p>We have four tests:<code>GetFuncWithClosure_InvokeOnce_GetExpectedResult<\/code>, <code>GetFuncWithClosure_InvokeMoreThanOnce_GetUnexpectedResult<\/code>, <code>GetFuncWithoutClosure_InvokeOnce_GetExpectedResult<\/code>, <code>GetFuncWithoutClosure_InvokeMoreThanOnce_GetExpectedResult<\/code>.<\/p>\n\n\n\n<p>First two tests test <code>GetFuncWithClosure<\/code>, whereas next two test <code>GetFuncWithoutClosure<\/code> method. Surprisingly, <code>GetFuncWithClosure<\/code>throws the DivideByZeroException exception, when <code>GetFuncWithClosure<\/code> invoked second time.<\/p>\n\n\n\n<p>To get better insights we should go to the <a href=\"https:\/\/sharplab.io\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"sharplab.io\">sharplab.io<\/a>.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Behind the scenes<\/h1>\n\n\n\n<p>If we paste our code in <a href=\"https:\/\/sharplab.io\/\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"sharplab.io\">sharplab.io<\/a>, we will get the answer of the DivideByZeroException exception occurrence cause. So, let&#8217;s take a closer look at the following:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1571\" height=\"908\" src=\"https:\/\/baldsolutions.com\/wp-content\/uploads\/2022\/03\/image-6.png\" alt=\"\" class=\"wp-image-257\" srcset=\"https:\/\/baldsolutions.com\/wp-content\/uploads\/2022\/03\/image-6.png 1571w, https:\/\/baldsolutions.com\/wp-content\/uploads\/2022\/03\/image-6-300x173.png 300w, https:\/\/baldsolutions.com\/wp-content\/uploads\/2022\/03\/image-6-1024x592.png 1024w, https:\/\/baldsolutions.com\/wp-content\/uploads\/2022\/03\/image-6-768x444.png 768w, https:\/\/baldsolutions.com\/wp-content\/uploads\/2022\/03\/image-6-1536x888.png 1536w\" sizes=\"auto, (max-width: 1571px) 100vw, 1571px\" \/><\/figure>\n\n\n\n<p>For now let&#8217;s focus on the problematic <code>GetFuncWithClosure<\/code>method. As you can see the method body uses now some strange <code>&lt;>c__DisplayClass0_0<\/code> class. Well, that is the exact example of the closure in C#. Compiler had to create something (<code>&lt;>c__DisplayClass0_0<\/code> class) to store the <code>int internalVariable<\/code> just because the variable has been used inside the returned Func&lt;int>.  On the other hand, <code>GetFuncWithoutClosure<\/code>method doesn&#8217;t use any external data within returned Func&lt;int, int>, therefore no corresponding *DisplayClass*.<\/p>\n\n\n\n<p>Once we know that, it&#8217;s obvious why the DivideByZeroException exception occurs.  First invocation (i.e. <code>func()<\/code>) subtracts 5 from the  <code>&lt;&gt;c__DisplayClass0_0<\/code> object&#8217;s <code>internalVariable<\/code>. So far so good, but second invocation subtracts 5 again from the  <code>&lt;&gt;c__DisplayClass0_0<\/code> object&#8217;s <code>internalVariable<\/code> zeroing its value. One thing is certain: Math does not like to divide by zero.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Summary<\/h1>\n\n\n\n<p>To sum up, closure is an interesting part of computer programming that definitely deserves to be understood. The above example shows that the code might work in an unexpected manner, until we don&#8217;t know what happens behind the scenes. To get better understanding what the closure is I highly recommend to read some articles\/blogs (including aforementioned <a href=\"https:\/\/en.wikipedia.org\/wiki\/Closure_(computer_programming)\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Wikipedia \">Wikipedia <\/a>page) or watch some YouTube video (e.g. <a href=\"https:\/\/www.youtube.com\/watch?v=h3MsnBRqzcY&amp;ab_channel=NickChapsas\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"this\">this<\/a> one).<\/p>\n\n\n\n<p>As always I&#8217;ve prepared an example and you can find it on my <a href=\"https:\/\/github.com\/tglowka\/baldsolutions\/tree\/master\/.NET\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"github\">github<\/a>, project: <a href=\"https:\/\/github.com\/tglowka\/baldsolutions\/tree\/master\/.NET\/closure\" target=\"_blank\" rel=\"noreferrer noopener\">closure<\/a>, test project: <a href=\"https:\/\/github.com\/tglowka\/baldsolutions\/tree\/master\/.NET\/closure-tests\" target=\"_blank\" rel=\"noreferrer noopener\">closure-tests.<\/a> I encourage you to go through the code, debug it and try to test your own scenarios.<\/p>\n\n\n\n<p>Have a nice day, bye!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction Closure itself isn&#8217;t a brand new topic. I&#8217;ve seen many blog articles that explain the topic (there&#8217;s even a Wikipedia page in a few&#8230;<\/p>\n<div class=\"more-link-wrapper\"><a class=\"more-link\" href=\"https:\/\/baldsolutions.com\/index.php\/2022\/03\/19\/closure-unexpected-exception\/\">Continue reading<span class=\"screen-reader-text\">Closure &#8211; unexpected exception<\/span><\/a><\/div>\n","protected":false},"author":3,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[2],"tags":[],"class_list":["post-245","post","type-post","status-publish","format-standard","hentry","category-net","entry"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/posts\/245","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/comments?post=245"}],"version-history":[{"count":30,"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/posts\/245\/revisions"}],"predecessor-version":[{"id":278,"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/posts\/245\/revisions\/278"}],"wp:attachment":[{"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/media?parent=245"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/categories?post=245"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/tags?post=245"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}