{"id":62,"date":"2009-11-14T19:52:26","date_gmt":"2009-11-14T19:52:26","guid":{"rendered":"http:\/\/www.thewiredguy.com\/wordpress\/?p=62"},"modified":"2009-11-14T19:52:26","modified_gmt":"2009-11-14T19:52:26","slug":"just-another-way-to-analyse-code-behaviour-in-my-humble-opinion","status":"publish","type":"post","link":"https:\/\/inullable.in\/blog\/?p=62","title":{"rendered":"Just another way to analyse code behaviour &#8211; In my humble opinion"},"content":{"rendered":"<p>Last week, a good <a href=\"http:\/\/www.facebook.com\/kinnarshah\" target=\"_blank\">friend<\/a> of mine posted a question on his <a href=\"http:\/\/www.kinnarshah.in\/index.php\/2009\/11\/04\/interesting-linq-problem\/\" target=\"_blank\">blog<\/a>, which track backs to <a href=\"http:\/\/blogs.msdn.com\/ericlippert\/archive\/2009\/11\/02\/simple-names-are-not-so-simple.aspx\" target=\"_blank\">Eric Lippert&#8217;s<\/a> blog post <a href=\"http:\/\/blogs.msdn.com\/ericlippert\/archive\/2009\/11\/02\/simple-names-are-not-so-simple.aspx\">Simple names are not so simple<\/a>. <\/p>\n<p><u>Side Note<\/u>: I am big fan of that blog, its awesome and enlightening<\/p>\n<p>Well, here is an excerpt of that post:<\/p>\n<blockquote>\n<p>Check out the code below:<\/p>\n<p>using System.Linq;      <br \/>class Program       <br \/>{       <br \/>&#160; static void Main()       <br \/>&#160; {&#160; <br \/>&#160;&#160;&#160;&#160;&#160; int[] data = { 1, 2, 3, 1, 2, 1 };       <br \/>&#160;&#160;&#160;&#160;&#160; foreach (<strong>var m in from m in data orderby m select m<\/strong>)       <br \/>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; System.Console.Write(m);       <br \/>&#160; }       <br \/>}<\/p>\n<p><a href=\"http:\/\/www.kinnarshah.in\/wp-content\/uploads\/2009\/11\/frustration3.jpg\"><img loading=\"lazy\" title=\"frustration3\" border=\"0\" alt=\"frustration3\" align=\"left\" src=\"http:\/\/www.kinnarshah.in\/wp-content\/uploads\/2009\/11\/frustration3_thumb.jpg\" width=\"146\" height=\"119\" \/><\/a><\/p>\n<p>Now, the question is:<\/p>\n<p>&#160; Is this code valid or not?? <\/p>\n<p>&#160; If valid, how? <\/p>\n<p>&#160; If not valid, why? <\/p>\n<p><strong>(Source: Eric Lippert&#8217;s Blog)<\/strong>&#160; <\/p>\n<\/blockquote>\n<p>So, I worked on that problem posted some comments there, and presenting it again here in the form of a post. <\/p>\n<p>The moment I read the problem, things started running in my mind around <\/p>\n<p><strong>var m in from m in data orderby m select m<\/strong> <\/p>\n<p>as you can perceive, m is being used in two different contexts, first as a enumerator in LINQ query: &quot; from m in data orderby m select m &quot; <\/p>\n<p>and the &quot;var m &quot; part in foreach. The question here: <strong>Can that possibly work?<\/strong> <\/p>\n<p>Luckily, I was honing my skills in Reflection (System.Reflection) at that time, I get across a phrase in this book about foreach block (it says Cs compiler adds some temp. variable to smooth out operations like <\/p>\n<blockquote>\n<p>a += 2; <\/p>\n<p>or <\/p>\n<p>foreach(var m in M){}<\/p>\n<\/blockquote>\n<p>along with that there was also a prenotion that something &quot;magical&quot; happens when you encounter such situation, and whole code behaves like it is working in scopes (The blocks of { }). <\/p>\n<p>So, the possible explanation, that came to my mind about this problem was : <\/p>\n<p>the thing &quot;<strong>var m in from m in data orderby m select m<\/strong>&quot; <\/p>\n<p>breaks up into two scopes : { var m } in { from m in data orderby m select m } <\/p>\n<p>or in other terms var m in {from m in data orderby m select m} <\/p>\n<p>We can proceed to further abstractions <\/p>\n<p>var m = {from m&#8217; in data order by m&#8217; select m&#8217;} <\/p>\n<p>that would eventually looks like <\/p>\n<p>var m in m&#8217; \/\/ where m&#8217; is enumerable <\/p>\n<p>[ \ud83d\ude2e Oops, m&#8217; is not a valid name for a variable, but good for human beings] <\/p>\n<p>&#160; <\/p>\n<p>OK! I have a possible explanation, now how to confirm that its right and not a conjecture. <\/p>\n<p>I fired <a href=\"http:\/\/www.rssbandit.org\" target=\"_blank\">RSS Bandit<\/a> and rushed to Eric Lippert&#8217;s blog&#8230; <\/p>\n<blockquote>\n<p>&lt;digression&gt; <\/p>\n<p>x-( <\/p>\n<p>Though I like reading blogs, but Internet, blogs and twitter (a.k.a Knowledge Supernova) provide so much information to absorb, I occasionally procrastinate reading RSS and let them aggregate scheduled to be read on weekends, after I am exhausted&#160; from celebrating TGIF and TGIS, so I missed the Eric Lipperts blog post that mentioned this problem \ud83d\ude41 <\/p>\n<p>&lt;\/digression&gt; <\/p>\n<\/blockquote>\n<p>I fired <a href=\"http:\/\/www.rssbandit.org\" target=\"_blank\">RSS Bandit<\/a> and rushed to Eric Lippert&#8217;s blog and tried to find out where this problem is being discussed, and I failed to figure its occurrence since it was phrased at the end of blog post and I was flipping over top. <\/p>\n<p>This made me more curious to find the real answer, so I fired VS, hit Ctrl + C, Ctrl+ V and some tabs, ran it and yes it was running fine, just like you would expect. <\/p>\n<p><a href=\"http:\/\/thewiredguy.com\/BlogImages\/JustanotherwaytoanalysecodebehaviourInmy_F88\/image.png\"><img loading=\"lazy\" border=\"0\" alt=\"image\" src=\"http:\/\/thewiredguy.com\/BlogImages\/JustanotherwaytoanalysecodebehaviourInmy_F88\/image_thumb.png\" width=\"677\" height=\"342\" \/><\/a><\/p>\n<p>But, that doesn&#8217;t answer actually what concerns me: Is my explanation is completely right?<\/p>\n<p>Suddenly, an idea struck me: Utilize Reflection<\/p>\n<p>Advantage was that, it will cause extra practice much needed to get comfortable with reflection<\/p>\n<p>So, I started writing code:<\/p>\n<p>First, I wrote <\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">using<\/span> System.Linq;\n<span class=\"kwrd\">using<\/span> System.Reflection;\n<span class=\"kwrd\">using<\/span> System.Reflection.Emit;\n<span class=\"kwrd\">using<\/span> System.Collections.Generic;\n    <span class=\"kwrd\">class<\/span> Program \n    { \n      <span class=\"kwrd\">static<\/span> <span class=\"kwrd\">void<\/span> Main() \n      {  \n         <span class=\"kwrd\">int<\/span>[] data = { 1, 2, 3, 1, 2, 1 }; \n\n          <span class=\"kwrd\">foreach<\/span> (var m <span class=\"kwrd\">in<\/span> from m <span class=\"kwrd\">in<\/span> data orderby m select m)\n             System.Console.Write(m); \n\n          <span class=\"kwrd\">new<\/span> Analyse().Run(); \n\n          System.Console.ReadKey();\n      } \n    } \n\n    <span class=\"kwrd\">class<\/span> Analyse\n    {\n        <span class=\"kwrd\">public<\/span> <span class=\"kwrd\">void<\/span> Run()\n        {\n            Assembly asm = Assembly.GetAssembly(<span class=\"kwrd\">typeof<\/span>(Program));\n            MethodBody mb = asm.EntryPoint.GetMethodBody();\n            System.Console.WriteLine(<span class=\"str\">&quot;nMethod Name: &quot;<\/span>+asm.EntryPoint.Name);\n            <span class=\"kwrd\">foreach<\/span> (var locals <span class=\"kwrd\">in<\/span> mb.LocalVariables)\n            {\n                System.Console.WriteLine(<span class=\"str\">&quot;n {0}&quot;<\/span>, locals.LocalType.FullName);\n            }\n            System.Console.ReadKey();\n        }\n    }<\/pre>\n<p>The Run method would actually list all the variables that are present after actual compilation, this will include the variables we have declared explicitly or implicitly as well as other variables introduced by compiler to store temporary results and perform calculations.<\/p>\n<p>If you run it you will get output:<\/p>\n<blockquote>\n<p>&#160; <\/p>\n<p>111223 <\/p>\n<p>Method Name: Main <\/p>\n<p>System.Int32[] <\/p>\n<p>System.Int32 <\/p>\n<p>System.Collections.Generic.IEnumerator`1[[System.Int32, mscorlib, Version=2.0.0.<br \/>\n    <br \/>0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] <\/p>\n<p>System.Boolean<\/p>\n<\/blockquote>\n<p>Ok! Let me set a context, before I go for explaining things here <\/p>\n<p>change the body of main() method inside program class to<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">using<\/span> System.Linq;\n<span class=\"kwrd\">using<\/span> System.Reflection;\n<span class=\"kwrd\">using<\/span> System.Reflection.Emit;\n<span class=\"kwrd\">using<\/span> System.Collections.Generic;\n    \n    <span class=\"kwrd\">class<\/span> Program \n    { \n      <span class=\"kwrd\">static<\/span> <span class=\"kwrd\">void<\/span> Main() \n      {  \n         <span class=\"kwrd\">int<\/span>[] data = { 1, 2, 3, 1, 2, 1 };\n        \n          <span class=\"kwrd\">foreach<\/span> (var num <span class=\"kwrd\">in<\/span> data)\n          {\n              System.Console.Write(num);\n          }\n\n          <span class=\"kwrd\">new<\/span> Analyse().Run();\n\n          System.Console.ReadKey();\n      } \n    }\n... contd.<\/pre>\n<style type=\"text\/css\">\n<p>.csharpcode, .csharpcode pre\n{\n\tfont-size: small;\n\tcolor: black;\n\tfont-family: consolas, \"Courier New\", courier, monospace;\n\tbackground-color: #ffffff;\n\t\/*white-space: pre;*\/\n}\n.csharpcode pre { margin: 0em; }\n.csharpcode .rem { color: #008000; }\n.csharpcode .kwrd { color: #0000ff; }\n.csharpcode .str { color: #006080; }\n.csharpcode .op { color: #0000c0; }\n.csharpcode .preproc { color: #cc6633; }\n.csharpcode .asp { background-color: #ffff00; }\n.csharpcode .html { color: #800000; }\n.csharpcode .attr { color: #ff0000; }\n.csharpcode .alt \n{\n\tbackground-color: #f4f4f4;\n\twidth: 100%;\n\tmargin: 0em;\n}\n.csharpcode .lnum { color: #606060; }<\/style>\n<\/p>\n<p>How the output changes:<\/p>\n<blockquote>\n<p>123121 <\/p>\n<p>Method Name: Main <\/p>\n<p>System.Int32[] <\/p>\n<p>System.Int32 <\/p>\n<p>System.Int32[] <\/p>\n<p>System.Int32 <\/p>\n<p>System.Boolean<\/p>\n<\/blockquote>\n<p><u>A little explanation<\/u> <\/p>\n<p>&#160; <\/p>\n<blockquote>\n<p>the first system.Int32[] is this array int[ ] data = { 1, 2, 3, 1, 2, 1 }; <\/p>\n<p>next System.Int32 will receive value at each iteration and will be used in Write() [this is our var m] <\/p>\n<p>the second System.Int32[] refers to ForEach&#8217;s copy of array. Remember foreach doesn&#8217;t allow changing contents, so it makes a copy. <\/p>\n<p>the second Int32 is an index to track current iterator location <\/p>\n<p>last is a boolean which stores the result of condition check<\/p>\n<\/blockquote>\n<p><strong><\/strong>&#160;<\/p>\n<p><strong>Note<\/strong>: this is again guess work, but still quiet predictable <img alt=\":P\" src=\"http:\/\/www.kinnarshah.in\/wp-includes\/images\/smilies\/icon_razz.gif\" \/><\/p>\n<p>Note that there are two occurrence of System.Int32, than how can I figure out, what is the purpose of the second one and last one<\/p>\n<p>so, we again change the main() body to<\/p>\n<p>&#160;<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">static<\/span> <span class=\"kwrd\">void<\/span> Main() \n      {  \n\n         <span class=\"kwrd\">char<\/span>[] ch = { <span class=\"str\">'a'<\/span>, <span class=\"str\">'b'<\/span>, <span class=\"str\">'c'<\/span> };\n\n         <span class=\"kwrd\">foreach<\/span> (var num <span class=\"kwrd\">in<\/span> ch)\n         {\n             System.Console.Write(num);\n         }\n\n          <span class=\"kwrd\">new<\/span> Analyse().Run();\n\n          System.Console.ReadKey();\n      } \n...\n..<\/pre>\n<style type=\"text\/css\">\n<p>.csharpcode, .csharpcode pre\n{\n\tfont-size: small;\n\tcolor: black;\n\tfont-family: consolas, \"Courier New\", courier, monospace;\n\tbackground-color: #ffffff;\n\t\/*white-space: pre;*\/\n}\n.csharpcode pre { margin: 0em; }\n.csharpcode .rem { color: #008000; }\n.csharpcode .kwrd { color: #0000ff; }\n.csharpcode .str { color: #006080; }\n.csharpcode .op { color: #0000c0; }\n.csharpcode .preproc { color: #cc6633; }\n.csharpcode .asp { background-color: #ffff00; }\n.csharpcode .html { color: #800000; }\n.csharpcode .attr { color: #ff0000; }\n.csharpcode .alt \n{\n\tbackground-color: #f4f4f4;\n\twidth: 100%;\n\tmargin: 0em;\n}\n.csharpcode .lnum { color: #606060; }<\/style>\n<p>the output changes to :<\/p>\n<blockquote>\n<p>abc <\/p>\n<p>Method Name: Main <\/p>\n<p>System.Char[] <\/p>\n<p>System.Char <\/p>\n<p>System.Char[] <\/p>\n<p>System.Int32 <\/p>\n<p>System.Boolean<\/p>\n<\/blockquote>\n<p>so, you can see that, system.char (replacing first System.Int32) is getting the assigned value that will be Write() outputted, and thus by comparing the ordinal similarity between the two outputs, it would be right to think that first System.Int32 is receiving the current value of data (index to which, iteration is pointing). <\/p>\n<p>Back to our actual code, analysing the output <\/p>\n<blockquote>\n<p>111223 <\/p>\n<p>Method Name: Main <\/p>\n<p>System.Int32[] <\/p>\n<p>System.Int32 <\/p>\n<p>System.Collections.Generic.IEnumerator`1[[System.Int32, mscorlib, Version=2.0.0.<br \/>\n    <br \/>0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] <\/p>\n<p>System.Boolean<\/p>\n<\/blockquote>\n<p>line by line, we can see that <\/p>\n<p><em>System.Int32[ ]<\/em> <\/p>\n<p>(the actual data[] array) <\/p>\n<p><em>System.Int32<br \/>\n    <br \/><\/em>(that will receive value at each iteration and will be WriteLined\/outputted) <\/p>\n<p><em>System.Collections.Generic.IEnumerator`1[[System.Int32, mscorlib blah blah blah&#8230; ]]<\/em><\/p>\n<p><em><\/em><\/p>\n<p>( the generic IEnumerator generated from LINQ expression obtained, now all classes implementing IEnumerator has a method called MoveNext( ), hence it will not require any additional Sytem.int32 indexer, hence here it is absent in output)<\/p>\n<p><em>System.Boolean<br \/>\n    <br \/><\/em>(condition check result as previously stated) <\/p>\n<p>From all this, we get that compiler handle duplicate references smartly, until we play by his rules and work according to C# language specs \ud83d\ude42 <\/p>\n<p>This technique forms (No, I didn&#8217;t discovered it) another tool to analyse the code behaviour. <\/p>\n<p>As a side note, other such techniques you are familiar with are: <\/p>\n<ul>\n<li>looking at preprocessor output (those *.i files in C) <\/li>\n<li>looking at post compile code <\/li>\n<li>Looking at generated assembly code <\/li>\n<li>running ILDASM x-( <\/li>\n<li>debugging?? <\/li>\n<li>blah blah blah (ask a real Expert, he will provide you an exhaustive list of such techniques) <\/li>\n<p>  <u><strong><\/strong><\/u><\/ul>\n<ul><strong><u>THE HAPPY ENDING<\/u><\/strong><\/p>\n<blockquote>\n<p>finally, on the other day when I was reading posts aggregated in RSS Bandit from coding horror, many other blogs and somewhere in middle Eric&#8217;s blog, I find this problem hiding at the bottom of the blog post, and by reading the blog post you can get the explanation and It seems that, I stand correct :)Still if you think, I am wrong somewhere, please comment here. I will be happy to get the right facts.<\/p>\n<\/blockquote>\n<\/ul>\n<p><strong>Edit: <\/strong>I just found out that, Eric also posted next <a href=\"http:\/\/blogs.msdn.com\/ericlippert\/archive\/2009\/11\/05\/simple-names-are-not-so-simple-part-two.aspx\" target=\"_blank\">post<\/a> in continuation to that problem, where he explains excellently the behaviour of this code, in his own way.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Last week, a good friend of mine posted a question on his blog, which track backs to Eric Lippert&#8217;s blog post Simple names are not so simple. Side Note: I am big fan of that blog, its awesome and enlightening Well, here is an excerpt of that post: Check out the code below: using System.Linq; [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[11,71,101],"tags":[],"_links":{"self":[{"href":"https:\/\/inullable.in\/blog\/index.php?rest_route=\/wp\/v2\/posts\/62"}],"collection":[{"href":"https:\/\/inullable.in\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/inullable.in\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/inullable.in\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/inullable.in\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=62"}],"version-history":[{"count":0,"href":"https:\/\/inullable.in\/blog\/index.php?rest_route=\/wp\/v2\/posts\/62\/revisions"}],"wp:attachment":[{"href":"https:\/\/inullable.in\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=62"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/inullable.in\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=62"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/inullable.in\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=62"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}