<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Fabulous Adventures In Coding</title>
	<atom:link href="http://ericlippert.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://ericlippert.com</link>
	<description>Eric Lippert&#039;s blog</description>
	<lastBuildDate>Mon, 17 Jun 2013 14:53:43 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>String concatenation behind the scenes, part one</title>
		<link>http://ericlippert.com/2013/06/17/string-concatenation-behind-the-scenes-part-one/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=string-concatenation-behind-the-scenes-part-one</link>
		<comments>http://ericlippert.com/2013/06/17/string-concatenation-behind-the-scenes-part-one/#comments</comments>
		<pubDate>Mon, 17 Jun 2013 14:20:25 +0000</pubDate>
		<dc:creator>Eric Lippert</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code generation]]></category>
		<category><![CDATA[string concatenation]]></category>

		<guid isPermaLink="false">http://ericlippert.com/?p=1228</guid>
		<description><![CDATA[The first algorithm I ever worked on in the C# compiler was the optimizer that handles string concatenations.1 It's all pretty straightforward, but there are a few clever bits that I thought I might discuss today. First off, let's consider &#8230; <a href="http://ericlippert.com/2013/06/17/string-concatenation-behind-the-scenes-part-one/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>The first algorithm I ever worked on in the C# compiler was the optimizer that handles string concatenations.<sup class="footnote"><a href="#fn-1228-1" id="fnref-1228-1" onclick="return fdfootnote_show(1228)">1</a></sup> It's all pretty straightforward, but there are a few clever bits that I thought I might discuss today.</p>
<p><span id="more-1228"></span></p>
<p>First off, let's consider just straight up concatenation of string variables; in fact, let's assume that all variables are strings for the purposes of this article. If you have:</p>
<pre>
r = a + b;
</pre>
<p>then clearly that is going to be generated as</p>
<pre>
r = String.Concat(a, b);
</pre>
<p>But what about</p>
<pre>
r = a + b + c;
</pre>
<p>? String addition, like all addition in C#, is left associative, so this is the same as</p>
<pre>
r = (a + b) + c;
</pre>
<p>So you might think that would be generated as</p>
<pre>
r = String.Concat(String.Concat(a, b), c);
</pre>
<p>but the compiler can be more efficient than that because there is an overload of <code>String.Concat</code> which takes three operands and produces the same result:</p>
<pre>
r = String.Concat(a, b, c);
</pre>
<p>Ditto for four operands. However when we get to five or more operands the compiler switches to a different overload:</p>
<pre>
r = a + b + c + d + e;
</pre>
<p>is generated as</p>
<pre>
r = String.Concat(new String[5] { a, b, c, d, e });
</pre>
<p>It's a bit unfortunate that you have to take on the cost of allocating an array, but there it is.</p>
<p>That's all very straightforward, but there are more optimizations that the C# compiler performs. The main optimization depends upon the fact that string concatenation is <strong>fully associative</strong>.<sup class="footnote"><a href="#fn-1228-2" id="fnref-1228-2" onclick="return fdfootnote_show(1228)">2</a></sup> That is, the parentheses don't matter. You might think that an oddity like</p>
<pre>
r = a + (b + c);
</pre>
<p>would have to be generated as</p>
<pre>
r = String.Concat(a, String.Concat(b, c));
</pre>
<p>but of course we can observe that since string concatenation is associative, this is no different than </p>
<pre>
r = (a + b) + c;
</pre>
<p>which we already know how to generate efficiently. The C# compiler's string optimizer automatically rewrites nested string concatenations into the left-parenthesized form no matter how you parenthesize them. Except when it doesn't, which is our next optimization. Let's now consider the impact of constants:</p>
<pre>
r = "A" + "B" + c;
</pre>
<p>The compiler will parse this as:</p>
<pre>
r = ("A" + "B") + c;
</pre>
<p>and of course that first term is a compile-time constant according to the spec. The compiler automatically computes values of compile-time constants, so this is the same as:</p>
<pre>
r = String.Concat("AB", c);
</pre>
<p>But what about this?</p>
<pre>
r = a + "B" + "C";
</pre>
<p>There are two compile-time constants, but this is parsed as</p>
<pre>
r = (a + "B") + "C";
</pre>
<p>Since both addition operators have a non-constant element on their left side, you might think this would have to be generated as</p>
<pre>
r = String.Concat(a, "B", "C");
</pre>
<p>But again associativity comes to the rescue. The optimizer notices that the original expression is the same as</p>
<pre>
r = a + ("B" + "C");
</pre>
<p>and generates</p>
<pre>
r = String.Concat(a, "BC");
</pre>
<p>And it will even do the right consolidation of constants "in the middle":</p>
<pre>
r = a + "B" + "C" + d;
</pre>
<p>is generated as though you'd said:</p>
<pre>
r = (a + ("B" + "C")) + d;
</pre>
<p>to produce</p>
<pre>
r = String.Concat(a, "BC", d);
</pre>
<p>The C# compiler also knows that empty string constants are the identity elements of concatenation; they are eliminated. If you say</p>
<pre>
r = a + "" + b;
</pre>
<p>Then the code generated is not</p>
<pre>
r = String.Concat(a, "", b);
</pre>
<p>but rather simply</p>
<pre>
r = String.Concat(a, b);
</pre>
<p>Null string constants are likewise identity elements:</p>
<pre>
const string NullString = null;
r = a + NullString + b;
</pre>
<p>is similarly generated as</p>
<pre>
r = String.Concat(a, b);
</pre>
<p>OK I must admit I just made a bald-faced lie there; did you catch it? </p>
<p>The null and empty strings are <strong>not</strong> identities of concatenation. An identity of an operator has the property that it leaves the other operand unchanged; zero is the identity of addition of numbers because any number plus zero gives you the original number. But there is one possible operand that is not preserved by addition with an empty or null string: the null string! <code>NullString + NullString</code> and <code>NullString + ""</code> both result in the empty string, not the null string, so neither is an identity.</p>
<p>You might think then that </p>
<pre>
r = a + NullString;
</pre>
<p>must be generated as</p>
<pre>
r = String.Concat(a, NullString);
</pre>
<p>because the compiler needs to ensure that if <code>a</code> is <code>null</code> then the result is the empty string. In fact the C# compiler anticipates what <code>String.Concat</code> will do and simply inlines it. This is generated the same as:</p>
<pre>
r = a ?? "";
</pre>
<p>which I think is a neat trick, to elide the concatenation entirely.</p>
<hr/>
<p><strong>Next time on FAIC:</strong> An optimization the C# compiler does <strong>not</strong> perform.</p>
<div class="footnotes" id="footnotes-1228">
<div class="footnotedivider"></div>
<ol>
<li id='fn-1228-1'>Unfortunately I did not manage to port these optimizations to the Roslyn codebase before I left; hopefully someone will get to that! <span class='footnotereverse'><a href='#fnref-1228-1'>&#8617;</a></span></li>
<li id='fn-1228-2'>And that <code>String.Concat</code> has no observable side effects. <span class='footnotereverse'><a href='#fnref-1228-2'>&#8617;</a></span></li>
</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://ericlippert.com/2013/06/17/string-concatenation-behind-the-scenes-part-one/feed/</wfw:commentRss>
		<slash:comments>26</slash:comments>
		</item>
		<item>
		<title>What&#039;s the difference? sizeof and Marshal.SizeOf</title>
		<link>http://ericlippert.com/2013/06/13/whats-the-difference-sizeof-and-marshal-sizeof/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=whats-the-difference-sizeof-and-marshal-sizeof</link>
		<comments>http://ericlippert.com/2013/06/13/whats-the-difference-sizeof-and-marshal-sizeof/#comments</comments>
		<pubDate>Thu, 13 Jun 2013 14:29:22 +0000</pubDate>
		<dc:creator>Eric Lippert</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[What's the difference?]]></category>

		<guid isPermaLink="false">http://ericlippert.com/?p=1225</guid>
		<description><![CDATA[I often see StackOverflow answers that confuse the sizeof operator with the Marshal.SizeOf method. These two operators do different things and can return different results, so it is important to know which is which. In a nutshell, the difference is: &#8230; <a href="http://ericlippert.com/2013/06/13/whats-the-difference-sizeof-and-marshal-sizeof/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>I often see StackOverflow answers that confuse the <code>sizeof</code> operator with the <code>Marshal.SizeOf</code> method. These two operators do different things and can return different results, so it is important to know which is which.</p>
<p>In a nutshell, the difference is: the <code>sizeof</code> operator takes a <strong>type name</strong> and tells you how many bytes of <strong>managed</strong> memory need to be allocated for an instance of that struct.<sup class="footnote"><a href="#fn-1225-1" id="fnref-1225-1" onclick="return fdfootnote_show(1225)">1</a></sup> By contrast, <code>Marshal.SizeOf</code> takes either a <strong>type object</strong> or an <strong>instance</strong> of the type, and tells you how many bytes of <strong>unmanaged</strong> memory need to be allocated. These can be different for a variety of reasons. The name of the type gives you a clue: <code>Marshal.SizeOf</code> is intended to be used when <I>marshaling</I> a structure to unmanaged memory.  </p>
<p>Another difference between the two is that the <code>sizeof</code> operator can only take the name of an <I>unmanaged</I> type; that is, a struct type whose fields are only integral types, Booleans, pointers and so on. (See the specification for an exact definition.) <code>Marshal.SizeOf</code> by contrast can take any class or struct type. </p>
<div class="footnotes" id="footnotes-1225">
<div class="footnotedivider"></div>
<ol>
<li id='fn-1225-1'>I don't have to tell long-time readers of this blog that of course this is not necessarily stack memory; structs are allocated off the heap when they are array elements, fields of a class, and so on. <span class='footnotereverse'><a href='#fnref-1225-1'>&#8617;</a></span></li>
</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://ericlippert.com/2013/06/13/whats-the-difference-sizeof-and-marshal-sizeof/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
		<item>
		<title>Construction destruction</title>
		<link>http://ericlippert.com/2013/06/10/construction-destruction/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=construction-destruction</link>
		<comments>http://ericlippert.com/2013/06/10/construction-destruction/#comments</comments>
		<pubDate>Mon, 10 Jun 2013 14:28:59 +0000</pubDate>
		<dc:creator>Eric Lippert</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Thread safety]]></category>

		<guid isPermaLink="false">http://ericlippert.com/?p=1203</guid>
		<description><![CDATA[Take a look at this little program skeleton: class Foo { private int x; private int y; public Foo(int x, int y) { this.x = x; this.y = y; SideEffects.Alpha(); // Notice: does not use "this" } ~Foo() { SideEffects.Charlie(); &#8230; <a href="http://ericlippert.com/2013/06/10/construction-destruction/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Take a look at this little program skeleton:</p>
<pre>
class Foo 
{ 
    private int x;
    private int y;
    public Foo(int x, int y) 
    {
        this.x = x;
        this.y = y;
        SideEffects.Alpha(); // Notice: does not use "this"
    }
    ~Foo() 
    { 
        SideEffects.Charlie(); 
    }
}
static class SideEffects
{
    public static void Alpha() { ... }
    public static void Bravo() { ... }
    public static void Charlie() { ... }
    public static void M()
    {
        Foo foo = new Foo(1, 2); 
        Bravo();
    }
}
</pre>
<p>Let's suppose we have three side effects: <code>Alpha</code>, <code>Bravo</code> and <code>Charlie</code>. What precisely they are is not important.</p>
<p>The question is: what do we know about the order in which <code>Alpha</code>, <code>Bravo</code> and <code>Charlie</code> execute when a call to <code>M()</code> occurs?<br />
<span id="more-1203"></span><br />
First off, clearly <code>Alpha</code> must happen before <code>Bravo</code>. The C# compiler and the jit compiler are not permitted to make any optimization that would cause the side effects of a single-threaded program to appear out of order. The construction of <code>foo</code> must be complete before control is passed to <code>Bravo</code>, which means that <code>Alpha</code> has already run.</p>
<p>You might think that <code>Charlie</code> has to happen after <code>Bravo</code> by the following reasoning: <code>Charlie</code> does not run until the object referred to by <code>foo</code> is garbage collected. The local <code>foo</code> is alive until the end of <code>M</code> and therefore it cannot be collected until after <code>Bravo</code>.</p>
<p>This reasoning is incorrect. The C# compiler and the jitter are both permitted to notice that <code>foo</code> is never read from after its initial write, and therefore it can be garbage collected before the end of <code>M</code>, and therefore can be garbage collected before <code>Bravo</code>. </p>
<p>But didn't I just say that the compilers were not permitted to make this optimization?  No, I did not. I said that they were not permitted to make this optimization in a single-threaded program, but the garbage collector and the finalizer queue run on their own threads! The C# language makes very few guarantees about how side effects are ordered in a multi-threaded program; only very special side effects like volatile writes, thread creation, and so on, are guaranteed to be observed in a particular order.</p>
<p>So it is legal for <code>Charlie</code> to happen before -- or during! -- <code>Bravo</code>. But surely<sup class="footnote"><a href="#fn-1203-1" id="fnref-1203-1" onclick="return fdfootnote_show(1203)">1</a></sup> <code>Charlie</code> happens after <code>Alpha</code>?</p>
<p>Nope! This isn't guaranteed either. The jitter can notice that <code>foo</code> is never read from and is therefore useless; it can throw it away entirely. The jitter can then notice that neither the reference to <code>this</code> nor fields <code>x</code> and <code>y</code> are ever used after <code>this.y = y;</code>, and mark the object as a candidate for finalization before <code>Alpha</code>. It is possible for an object to be destructed while its constructor is running on another thread! </p>
<p>This is of course extremely unlikely, but it is legal, and therefore you have to assume the worst. This is yet another reason why it is so difficult to write a correct destructor in .NET; you can't assume that the constructor finished before the destructor runs, so any invariants that you're setting up in your constructor are not necessarily valid in the destructor.</p>
<p>So what do you do if you're in this crazy situation and you require <code>Charlie</code> to run after <code>Bravo</code>?</p>
<pre>
    public static void M()
    {
        Foo foo = new Foo(1, 2); 
        Bravo();
        GC.KeepAlive(foo);
    }
</pre>
<p>The <code>GC.KeepAlive</code> method is a very special method that tells the jitter and the garbage collector that the lifetime of <code>foo</code> must be extended to at least this point. Make sure you understand that: when you call <code>KeepAlive</code>, the object is alive before the call and possibly dead after the call.</p>
<p>Of course, the far better thing to do would be to make <code>Foo</code> expose its cleanup<sup class="footnote"><a href="#fn-1203-2" id="fnref-1203-2" onclick="return fdfootnote_show(1203)">2</a></sup> and simply say:</p>
<pre>
    public static void M()
    {
        Foo foo = new Foo(1, 2);
        Bravo();
        foo.Close();
    }
</pre>
<p>and then have <code>Charlie</code> run in the <code>Close</code>. Now we're on one thread again and the side effects must be correctly ordered. If the order of the calls is important for the correct functioning of the program then let's write a program that <em>obviously </em>calls them in the right order.</p>
<div class="footnotes" id="footnotes-1203">
<div class="footnotedivider"></div>
<ol>
<li id='fn-1203-1'>There it is again. <span class='footnotereverse'><a href='#fnref-1203-1'>&#8617;</a></span></li>
<li id='fn-1203-2'>Possibly via <code>IDisposable</code> if the side effects in question are cleaning up an unmanaged resource <span class='footnotereverse'><a href='#fnref-1203-2'>&#8617;</a></span></li>
</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://ericlippert.com/2013/06/10/construction-destruction/feed/</wfw:commentRss>
		<slash:comments>36</slash:comments>
		</item>
		<item>
		<title>An integer division identity</title>
		<link>http://ericlippert.com/2013/06/04/an-integer-division-identity/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=an-integer-division-identity</link>
		<comments>http://ericlippert.com/2013/06/04/an-integer-division-identity/#comments</comments>
		<pubDate>Tue, 04 Jun 2013 14:11:36 +0000</pubDate>
		<dc:creator>Eric Lippert</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Integer arithmetic]]></category>
		<category><![CDATA[Mathematics]]></category>

		<guid isPermaLink="false">http://ericlippert.com/?p=1196</guid>
		<description><![CDATA[Here's an interesting question that came up on StackOverflow the other day: we know in "real" algebra that the equation (a / b) / c = a / (b * c) is an "identity"; it is true for any values &#8230; <a href="http://ericlippert.com/2013/06/04/an-integer-division-identity/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Here's <a href="http://stackoverflow.com/questions/16837854/">an interesting question that came up on StackOverflow </a>the other day: we know in "real" algebra that the equation <code>(a / b) / c = a / (b * c)</code> is an "identity"; it is true for any values of <code>a</code>, <code>b</code>, and <code>c</code>.<sup class="footnote"><a href="#fn-1196-1" id="fnref-1196-1" onclick="return fdfootnote_show(1196)">1</a></sup> <strong>Does this identity hold for integer arithmetic in C#?</strong></p>
<p><span id="more-1196"></span></p>
<p>In general, no, because of overflow. In a checked context the right side can overflow and produce an exception but the left side cannot. In an unchecked context two large positive values for <code>b</code> and <code>c</code> can overflow to a negative number on the right hand side, thereby producing a different result than the left hand side.</p>
<p>Moreover, commenter "Peter" points out that if <code>b</code> is <code>-1</code> then <code>(a/b)</code> can overflow too; I hadn't thought about that case, so good catch.</p>
<p>But what about the specific case where <code>a</code>, <code>b</code>, and <code>c</code> are positive numbers and there are no overflows in either expression? Can we rely on this identity under those circumstances?</p>
<p>Let's find out!</p>
<p>We begin by going back to the definition of integer division; as I've described before, there are two operators: the division operator and the remainder operator. Suppose we have (again supposing that <code>x</code> and <code>y</code> are positive integers):</p>
<p><code>r = x % y</code><br />
<code>q = x / y</code></p>
<p>The relationship between those values is:</p>
<p><code>x = q * y + r</code></p>
<p>where <code>0 &lt;= r &lt; y</code></p>
<p>Let's break our suspected identity apart into left and right sides. Let's say that the first division on the left side is:</p>
<p><code>q<sub>ab</sub> = a / b</code><br />
<code>r<sub>ab</sub> = a % b</code><br />
<code>b * q<sub>ab</sub> + r<sub>ab</sub> = a</code><br />
<code>0 &lt;= r<sub>ab</sub> &lt; b</code></p>
<p>So our left hand side is <code>q<sub>ab</sub> / c</code>. The quotient and remainder of that are:</p>
<p><code>q<sub>left</sub> = q<sub>ab</sub> / c</code><br />
<code>r<sub>left</sub> = q<sub>ab</sub> % c</code><br />
<code>c * q<sub>left</sub> + r<sub>left</sub> = q<sub>ab</sub></code><br />
<code>0 &lt;= r<sub>left</sub> &lt; c</code></p>
<p>We can eliminate <code>q<sub>ab</sub></code> through substitution to get the equation:</p>
<p><code>b * c * q<sub>left</sub> + b * r<sub>left</sub> + r<sub>ab</sub> = a</code></p>
<p>OK, that will do for the left hand side. For the right hand side we have just one division:</p>
<p><code>q<sub>right</sub> = a / (b * c)</code><br />
<code>r<sub>right</sub> = a % (b * c)</code><br />
<code>b * c * q<sub>right</sub> + r<sub>right</sub> = a</code><br />
<code>0 &lt;= r<sub>right</sub> &lt; b * c</code></p>
<p>We now have two equations that equal the same thing, <code>a</code>, so let's set them equal to each other:</p>
<p><code>b * c * q<sub>left</sub> + b * r<sub>left</sub> + r<sub>ab</sub> = b * c * q<sub>right</sub> + r<sub>right</sub></code></p>
<p>We know that <code>q<sub>left</sub></code> and <code>q<sub>right</sub></code> are both integers. Therefore there is an integer <code>d</code>, their difference, such that <code>q<sub>left</sub> + d = q<sub>right</sub>. Let's eliminate <code>q<sub>right</sub></code> from our equation:</code></p>
<p><code>b * c * q<sub>left</sub> + b * r<sub>left</sub> + r<sub>ab</sub> = b * c * q<sub>left</sub> + b * c * d + r<sub>right</sub></code></p>
<p>And solve for <code>d</code>:</p>
<p><code>d = (b * r<sub>left</sub> + r<sub>ab</sub> - r<sub>right</sub>) / (b * c)</code></p>
<p><code>d</code> is an integer. Is possibly positive? Let's make some inequalities. We know that <code>r<sub>right</sub></code> is non-negative, so the numerator of that fraction:</p>
<p><code>b * r<sub>left</sub> + r<sub>ab</sub> - r<sub>right</sub> &lt;= b * r<sub>left</sub> + r<sub>ab</sub></code></p>
<p>We know that <code>r<sub>left</sub> &lt; c</code> and <code>c &gt; 0</code> so</p>
<p><code>b * r<sub>left</sub> + r<sub>ab</sub> &lt;= b * (c - 1) + r<sub>ab</sub></code></p>
<p>We know that <code>r<sub>ab</sub> &lt; b</code>, so:</p>
<p><code>b * (c - 1) + r<sub>ab</sub> &lt; b * (c - 1) + b</code></p>
<p>But that's <code>b * c</code>. Therefore the numerator of this fraction is <strong>strictly less than its denominator, and therefore the fraction must be strictly less than one.</strong> Since the fraction is an integer, <code>d</code> must be zero or negative; it cannot be positive.</p>
<p>The proof that <code>d</code> also cannot be negative and therefore must be zero is similar and is left as an exercise.</p>
<p>Since <code>d</code> is zero, <code>q<sub>left</sub> = q<sub>right</sub></code>, which establishes the identity -- again, provided that all the operands are positive numbers and the multiplication does not overflow.</p>
<p>Proving that the identity works for negative <code>a</code>, <code>b</code> and <code>c</code> is also left as an exercise.</p>
<div class="footnotes" id="footnotes-1196">
<div class="footnotedivider"></div>
<ol>
<li id='fn-1196-1'>Assuming of course that both sides have a well-defined value. <span class='footnotereverse'><a href='#fnref-1196-1'>&#8617;</a></span></li>
</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://ericlippert.com/2013/06/04/an-integer-division-identity/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>What the meaning of is is</title>
		<link>http://ericlippert.com/2013/05/30/what-the-meaning-of-is-is/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=what-the-meaning-of-is-is</link>
		<comments>http://ericlippert.com/2013/05/30/what-the-meaning-of-is-is/#comments</comments>
		<pubDate>Thu, 30 May 2013 14:02:52 +0000</pubDate>
		<dc:creator>Eric Lippert</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Conversions]]></category>
		<category><![CDATA[is operator]]></category>

		<guid isPermaLink="false">http://ericlippert.com/?p=1173</guid>
		<description><![CDATA[Today a follow-up to my 2010 article about the meaning of the is operator. Presented as a dialog, as is my wont! I've noticed that the is operator is inconsistent in C#. Check this out: string s = null; // &#8230; <a href="http://ericlippert.com/2013/05/30/what-the-meaning-of-is-is/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Today a follow-up to <a href="http://blogs.msdn.com/b/ericlippert/archive/2010/09/16/is-is-as-or-is-as-is.aspx">my 2010 article</a> about the meaning of the <code>is</code> operator. Presented as a dialog, as is my wont!</p>
<blockquote><p>I've noticed that the <code>is</code> operator is inconsistent in C#. Check this out:</p></blockquote>
<pre>string s = null; // Clearly null is a legal value of type string
bool b = s is string; // But b is false!</pre>
<blockquote><p>What's up with that?</p></blockquote>
<p>Let's suppose you and I are neighbours.</p>
<blockquote><p>Um... ok, I'm not sure where this is going, but sure.</p></blockquote>
<p><span id="more-1173"></span></p>
<p>I'm looking into your driveway, which is empty. Can that driveway hold a Honda Civic?</p>
<blockquote><p>Sure, no problem. In fact, it frequently does.</p></blockquote>
<p>Now we cross the street and we look at my driveway, which is also empty. Can it hold a Honda Civic?</p>
<blockquote><p>Yes, I suppose so.</p></blockquote>
<p>In fact I have a rule that <i>only</i> Honda Civics may be parked in my driveway.</p>
<blockquote><p>That's a bit weird, but that's your business.</p></blockquote>
<p>Can the present contents of my driveway be placed in your driveway?</p>
<blockquote><p>Um... I don't know. That's a strange question. On the one hand I want to say that the question presupposes a false premise, namely that "the present contents of my empty driveway" refers to an object that can be moved from one place to another. On the other hand, the contents of our two empty driveways seem to be by definition "the same", namely, "zero Honda Civics". If you insist on an answer then I suppose I will have to say yes, the present contents of your driveway fit into my driveway.</p></blockquote>
<p>OK, so, does your driveway contain a Honda Civic?</p>
<blockquote><p>Obviously not. It's empty.</p></blockquote>
<p>Well, aren't you being inconsistent then? Let's review the facts.</p>
<ul>
<li>You agree that my driveway only contains Honda Civics.</li>
<li>You agree that the present contents of my driveway are identical to the contents of your driveway.</li>
<li>And yet you conclude that your driveway does not contain a Honda Civic!</li>
</ul>
<p>Either you are being inconsistent or there is something wrong with this logic.</p>
<blockquote><p>I'd agree with that! There's something wrong with your logic.</p></blockquote>
<p>And now we see why the <code>is</code> operator is actually consistent. The fact that a null reference may be assigned to a string variable does not make the null reference a string, any more than the fact that your driveway can be empty means that an empty driveway contains a Honda Civic. The <code>is</code> operator does not answer the question "can I assign this reference to a variable of the given type?" It answers the question "is this reference a legitimate reference to an object of the given type?", and null is not a legitimate reference.</p>
<blockquote><p>I'm beginning to see your point, but actually I never believed that the operator was answering a question about <strong>assignment compatibility</strong>. I believed that the operator was answering a question about <strong>type membership</strong>. <a href="http://www.youtube.com/watch?v=0A5t5_O8hdA">Surely the null reference is a member of the string type!</a></p></blockquote>
<p>Someone once told me that the fastest way to spot the weak point in an argument is to look for the "surely".</p>
<p>Actually, no. A common conception of types is that a type is a set, possibly infinite, of values, and that assignment compatibility is merely checking to see if a given value is a member of the necessary set. But that's not the case in C#. The null reference actually is not assigned any type at all; it is explicitly of no type, but it is assignment compatible with a variable of any reference type.<sup class="footnote"><a href="#fn-1173-1" id="fnref-1173-1" onclick="return fdfootnote_show(1173)">1</a></sup> The assignment compatibility relationship and the type membership relationship are similar in a lot of ways but they are not identical.</p>
<blockquote><p>Finally I know what the true meaning of what <code>is</code> is!</p></blockquote>
<p>Awesome! <a href="http://www.youtube.com/watch?v=j4XT-l-_3y0">Alert Bill Clinton!</a></p>
<p><strong>Next time on FAIC:</strong> <a title="An integer division identity" href="http://ericlippert.com/2013/06/04/an-integer-division-identity/">An interesting integer identity.</a></p>
<div class="footnotes" id="footnotes-1173">
<div class="footnotedivider"></div>
<ol>
<li id='fn-1173-1'>In C# 1.0 and 2.0 the specifications said that the null reference was the sole member of a special "null type", but this concept turned out to not be fruitful. You can't declare a variable of the null type, you can't use the null type as a generic type argument, basically it's a type that you can't actually use <em>as a type</em>. Mads deleted that concept from the C# 3.0 spec because it simply was not useful and caused more confusion than it prevented. <span class='footnotereverse'><a href='#fnref-1173-1'>&#8617;</a></span></li>
</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://ericlippert.com/2013/05/30/what-the-meaning-of-is-is/feed/</wfw:commentRss>
		<slash:comments>65</slash:comments>
		</item>
		<item>
		<title>Why so fabulous?</title>
		<link>http://ericlippert.com/2013/05/24/why-so-fabulous/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=why-so-fabulous</link>
		<comments>http://ericlippert.com/2013/05/24/why-so-fabulous/#comments</comments>
		<pubDate>Fri, 24 May 2013 14:16:55 +0000</pubDate>
		<dc:creator>Eric Lippert</dc:creator>
				<category><![CDATA[Introduction]]></category>
		<category><![CDATA[Non-computer]]></category>

		<guid isPermaLink="false">http://ericlippert.com/?p=1159</guid>
		<description><![CDATA[I can't believe it took almost ten years, but someone just asked me for the first time where the name of this blog comes from. Why "fabulous adventures"? Unsurprisingly, it's a private joke.1 When I was first an intern at &#8230; <a href="http://ericlippert.com/2013/05/24/why-so-fabulous/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>I can't believe it took almost ten years, but someone just asked me for the first time where the name of this blog comes from. Why "fabulous adventures"?<br />
<span id="more-1159"></span></p>
<p>Unsurprisingly, it's a private joke.<sup class="footnote"><a href="#fn-1159-1" id="fnref-1159-1" onclick="return fdfootnote_show(1159)">1</a></sup> When I was first an intern at Microsoft almost twenty years ago now I decided to be brave and go explore downtown Seattle.<sup class="footnote"><a href="#fn-1159-2" id="fnref-1159-2" onclick="return fdfootnote_show(1159)">2</a></sup> I got on the entirely wrong bus and ended up at some park-and-ride in the north end of the Eastside, which is the middle of a nigh endless suburbia, and did not realize my mistake until it was too late to do anything about it. It was just me and a very drunk man on the bus who kept telling me that I looked Australian. It took quite some doing to get back home again. I wrote this whole ridiculous story up in an email to my friends and family back home which I titled "FABULOUS ADVENTURES IN REDMOND". I sent home a number of FABULOUS ADVENTURES missives that winter and it got to be an inside joke. So naturally when I started a blog, the best possible title was immediately obvious to me.</p>
<p>So there you go. Not much of a <a href="http://xenon.xe.net/inthumor/ih_005.htm">secret science fiction origin story</a>, really.</p>
<p><strong>Next time on FAIC:</strong> I'm taking Memorial Day off; on Thursday we'll finally answer the age old question of <a title="What the meaning of is is" href="http://ericlippert.com/2013/05/30/what-the-meaning-of-is-is/">what the meaning of the word "is" is</a>.</p>
<div class="footnotes" id="footnotes-1159">
<div class="footnotedivider"></div>
<ol>
<li id='fn-1159-1'>Remember, the function of my sense of humour is to amuse <i>me</i>. <span class='footnotereverse'><a href='#fnref-1159-1'>&#8617;</a></span></li>
<li id='fn-1159-2'>Microsoft is of course headquartered in Redmond, across Lake Washington from Seattle proper. Everything to the east of the lake is called "the Eastside". <span class='footnotereverse'><a href='#fnref-1159-2'>&#8617;</a></span></li>
</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://ericlippert.com/2013/05/24/why-so-fabulous/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>The mystery of the inserted method</title>
		<link>http://ericlippert.com/2013/05/23/the-mystery-of-the-inserted-method/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=the-mystery-of-the-inserted-method</link>
		<comments>http://ericlippert.com/2013/05/23/the-mystery-of-the-inserted-method/#comments</comments>
		<pubDate>Thu, 23 May 2013 14:18:40 +0000</pubDate>
		<dc:creator>Eric Lippert</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://ericlippert.com/?p=1148</guid>
		<description><![CDATA[Today on FAIC, a detective story. Suppose you have this class in assembly Alpha.DLL: namespace Alpha { public class Bravo { public void Charlie() { System.Console.WriteLine("Alpha Bravo Charlie"); } } } Pretty straightforward. You call this method from assembly Delta.EXE &#8230; <a href="http://ericlippert.com/2013/05/23/the-mystery-of-the-inserted-method/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Today on FAIC, a detective story.<br />
<span id="more-1148"></span><br />
Suppose you have this class in assembly Alpha.DLL:</p>
<pre>
namespace Alpha
{
    public class Bravo
    {
        public void Charlie()
        {
            System.Console.WriteLine("Alpha Bravo Charlie");
        }
    }
}
</pre>
<p>Pretty straightforward. You call this method from assembly Delta.EXE like this:</p>
<pre>
namespace Delta
{
    public interface IFoxtrot
    {
        void Charlie();
    }
    public class Echo : Alpha.Bravo, IFoxtrot
    {
    }
    public class Program
    {
        static void Main()
        {
            IFoxtrot foxtrot = new Echo();
            foxtrot.Charlie();
        }
    }
}
</pre>
<p>Notice that class <code>Echo</code> does not re-implement <code>Charlie</code>, but that's fine; the base class implementation suffices to meet the requirements of interface <code>IFoxtrot</code>.  If we run this code and put a breakpoint on <code>Charlie</code> the call stack window in Visual Studio says:</p>
<pre>
Alpha.dll!Alpha.Bravo.Charlie()
[External Code]	
Delta.exe!Delta.Program.Main()
[External Code]	
</pre>
<p>It's unsurprising that there is "external code" inserted that calls <code>Main</code> for you, but what's with the "external code" between <code>Main</code> and <code>Charlie</code>? That should just be a straight call, right? Something strange is going on here.</p>
<p>It is possible for debugging purposes to <em>programmatically</em> inspect the call stack<sup class="footnote"><a href="#fn-1148-1" id="fnref-1148-1" onclick="return fdfootnote_show(1148)">1</a></sup> so let's change the implementation of <code>Charlie</code> to print out the caller. This let's us do a bit of an end-run around the debugger<sup class="footnote"><a href="#fn-1148-2" id="fnref-1148-2" onclick="return fdfootnote_show(1148)">2</a></sup> to see what is really happening there:</p>
<pre>
public void Charlie()
{
    System.Console.WriteLine("Alpha Bravo Charlie");
    System.Console.WriteLine((new System.Diagnostics.StackFrame(1).GetMethod().Name));
}
</pre>
<p>And now if we run it we get the output</p>
<pre>
Alpha Bravo Charlie
Delta.IFoxtrot.Charlie
</pre>
<p>What the heck is going on here?</p>
<p>What's going on is: the CLR requires that any method which implements an interface method be a virtual method, but the only candidate, <code>Alpha.Bravo.Charlie</code>, is non-virtual. Therefore when generating class <code>Echo</code>, the C# compiler actually generates the code as though you'd written:</p>
<pre>
    public class Echo : Alpha.Bravo, IFoxtrot
    {
        void Delta.IFoxtrot.Charlie()
        {
            base.Charlie();
        }
    }
</pre>
<p>The explicit interface implementation <i>is</i> a virtual method, satisfying the CLR. The compiler-generated method is marked as not having any source code, so the debugger writes <code>External code</code> in the call stack.</p>
<p>Mystery solved!</p>
<p><strong>Extra credit mystery</strong>: Why did I have to specify that <code>Echo</code> and <code>Bravo</code> be in different assemblies? Leave your guesses in the comments.</p>
<p><strong>Special thanks</strong> to Stack Overflow users Timwi and Jeff Moser for the <a href="http://stackoverflow.com/questions/3668322/">inspiration</a> for this blog post.</p>
<p><strong>Next time on FAIC:</strong> <a href="http://ericlippert.com/2013/05/24/why-so-fabulous/" title="Why so fabulous?">Just why are these adventures so fabulous anyway?</a></p>
<div class="footnotes" id="footnotes-1148">
<div class="footnotedivider"></div>
<ol>
<li id='fn-1148-1'>You should not do this for purposes other than debugging; the jitter is allowed to rearrange the call stack as it sees fit. Inlined methods do not appear on the call stack, tail recursive methods do not appear on the call stack, and so on. Use the <a href="http://msdn.microsoft.com/en-us/library/hh534540.aspx">caller information attributes</a> in C# 5 if you want to write a method that knows what its caller was. <span class='footnotereverse'><a href='#fnref-1148-1'>&#8617;</a></span></li>
<li id='fn-1148-2'>Commenter leppie points out that of course I have forgotten that Visual Studio has a "show external code on the call stack" feature that would have been a lot easier to use. I totally forgot about that. Silly me. <span class='footnotereverse'><a href='#fnref-1148-2'>&#8617;</a></span></li>
</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://ericlippert.com/2013/05/23/the-mystery-of-the-inserted-method/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Benchmarking mistakes, part two</title>
		<link>http://ericlippert.com/2013/05/21/benchmarking-mistakes-part-two/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=benchmarking-mistakes-part-two</link>
		<comments>http://ericlippert.com/2013/05/21/benchmarking-mistakes-part-two/#comments</comments>
		<pubDate>Tue, 21 May 2013 13:53:37 +0000</pubDate>
		<dc:creator>Eric Lippert</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[benchmarks]]></category>
		<category><![CDATA[tech.pro]]></category>

		<guid isPermaLink="false">http://ericlippert.com/?p=1167</guid>
		<description><![CDATA[Part two of my Tech.pro beginner-level series on how to write bad benchmarking code can be found here.]]></description>
				<content:encoded><![CDATA[<p>Part two of my <a href="https://tech.pro/">Tech.pro</a> beginner-level series on how to write bad benchmarking code can be found <a href="https://tech.pro/tutorial/1295/c-performance-benchmark-mistakes-part-two">here</a>. </p>
]]></content:encoded>
			<wfw:commentRss>http://ericlippert.com/2013/05/21/benchmarking-mistakes-part-two/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>What is lexical scoping?</title>
		<link>http://ericlippert.com/2013/05/20/what-is-lexical-scoping/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=what-is-lexical-scoping</link>
		<comments>http://ericlippert.com/2013/05/20/what-is-lexical-scoping/#comments</comments>
		<pubDate>Mon, 20 May 2013 14:01:13 +0000</pubDate>
		<dc:creator>Eric Lippert</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://ericlippert.com/?p=1136</guid>
		<description><![CDATA[Happy Eliza Doolittle day all; today seems like an appropriate day for careful elocution of technical jargon. So today, yet another question about "scope". As one of the more over-used jargon terms in programming languages, I get a lot of questions about &#8230; <a href="http://ericlippert.com/2013/05/20/what-is-lexical-scoping/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Happy <a href="http://www.youtube.com/watch?v=pwNKyTktDIE">Eliza Doolittle day</a> all; today seems like an appropriate day for careful elocution of technical jargon. So today, yet another question about "scope". As one of the more over-used jargon terms in programming languages, I get a lot of questions about it.</p>
<p>I'll remind you all again that in C# the term "scope" has a very carefully defined meaning: the <strong>scope</strong> of a named entity is the region of <strong>program text</strong> in which the <strong>unqualified </strong>name can be used to <strong>refer</strong> <strong>to</strong> the entity.<sup class="footnote"><a href="#fn-1136-1" id="fnref-1136-1" onclick="return fdfootnote_show(1136)">1</a></sup></p>
<p><span id="more-1136"></span></p>
<p>For example, the scope of a local variable is the text of the block which declares it. The scope of a private method is the text of the body of the class or struct which declares it. And so on; the C# specification has careful definitions which define the scope of everything that has a name.</p>
<p>The word "lexical" means, in a broad sense "relating to text", and clearly we have defined "scope" as being a relationship involving text, so is this kind of scoping also called "lexical scoping"?</p>
<p>Sort of, but not exactly. Let me explain.</p>
<p>Programming languages can be broadly divided into two categories: the <strong>lexically scoped languages</strong> and the <strong>dynamically scoped languages</strong>. The difference between the two is: in a lexically scoped language, the meaning of an unqualified name can be <strong>completely determined by looking at the program text</strong>; the analysis can be done "statically". In a dynamically scoped language the meaning of an unqualified name can change at runtime; the name analysis can only be done "dynamically".</p>
<p>Let me give you an example; it is easiest to show this with lambdas.</p>
<pre>class C
{
  public static Func&lt;int&gt; M()
  {
    int x = 123;
    return () =&gt; x;
  }
}
class P
{
  static void Main()
  {
    int x = 456;
    Func&lt;int&gt; f = C.M();
    System.Console.WriteLine(f());
  }
}</pre>
<p>The question is: what gets printed out? C# is a lexically scoped language, so the meaning of <code>x</code> in the lambda is determined at compile time, by analyzing the text <i>where the lambda was written</i>. C# prints out <code>123</code>. If C# were a dynamically scoped language then the meaning of <code>x</code> would be determined by analyzing the location <i>where the delegate was executed at runtime</i>, so it would print out <code>456</code>.</p>
<p>Dynamically scoped languages essentially make the C# definition of scope useless; any method that executes a lambda in a dynamically scoped language makes the region of program text in which its locals can be referred to by their names arbitrarily large.</p>
<p>JavaScript, though a very dynamic language, is actually for the most part lexically scoped:</p>
<pre>function M()
{
  var x = 123;
  return function () { return x; };
}
function N()
{
  var x = 456;
  var f = M();
  print(f()); // 123
}</pre>
<p>However, JavaScript does have one feature which makes it dynamically scoped:</p>
<pre>function Q(y)
{
  var x = 123;
  with(y)
    return x;
}
print(Q({ x : 456 })); // 456
print(Q(789));         // 123</pre>
<p>Here the meaning of unqualified name <code>x</code> changes at runtime depending on whether <code>y</code> has a member <code>x</code> or not. For this reason I recommend avoiding the <code>with</code> block in JavaScript; it makes it hard for the reader to understand the meaning of the program.</p>
<p>Most modern languages are lexically scoped; experience has shown that lexical scoping is easier on all concerned; developers and maintenance programmers have an easier time understanding lexically scoped languages, and compiler developers have an easier time writing efficient compilers. Some variants of Lisp use dynamic scoping, though Scheme requires lexical scoping. There are still a few dynamically scoped languages in common usage though; PostScript, the programming language which runs on printers, is perhaps the most commonly used of them.</p>
<hr/>
<p><strong>Next time on FAIC:</strong> We solve <a href="http://ericlippert.com/2013/05/23/the-mystery-of-the-inserted-method/" title="The mystery of the inserted method">the mystery of the inserted method</a>.</p>
<div class="footnotes" id="footnotes-1136">
<div class="footnotedivider"></div>
<ol>
<li id='fn-1136-1'>Scope is often confused with the closely related concepts of <strong>declaration space</strong> (the region of code in which no two things may be declared to have the same name), <strong>accessibility domain</strong> (the region of program text in which a member's accessibility modifier permits it to be looked up), and <strong>lifetime</strong> (the portion of the execution of the program during which the contents of a variable are not eligable for garbage collection.) <span class='footnotereverse'><a href='#fnref-1136-1'>&#8617;</a></span></li>
</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://ericlippert.com/2013/05/20/what-is-lexical-scoping/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Quality assurance fail</title>
		<link>http://ericlippert.com/2013/05/17/quality-assurance-fail/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=quality-assurance-fail</link>
		<comments>http://ericlippert.com/2013/05/17/quality-assurance-fail/#comments</comments>
		<pubDate>Fri, 17 May 2013 13:54:21 +0000</pubDate>
		<dc:creator>Eric Lippert</dc:creator>
				<category><![CDATA[Non-computer]]></category>

		<guid isPermaLink="false">http://ericlippert.com/?p=1141</guid>
		<description><![CDATA[Some fun for Friday. I just opened up a box containing a brand-new bit of telecommunications equipment, and the power supply arrived looking like this, fresh out of the box. (Click for a larger version.) How bad does your quality &#8230; <a href="http://ericlippert.com/2013/05/17/quality-assurance-fail/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><a href="http://ericlippert.com/wp-content/uploads/2013/05/PowerSupply.jpg"><img class="alignleft size-thumbnail wp-image-1142" alt="PowerSupply" src="http://ericlippert.com/wp-content/uploads/2013/05/PowerSupply-150x150.jpg" width="150" height="150" /></a>Some fun for Friday. I just opened up a box containing a brand-new bit of telecommunications equipment, and the power supply arrived looking like this, fresh out of the box. (Click for a larger version.)</p>
<p>How bad does your quality assurance have to be to ship to customers a power supply that cannot possibly fit into a power socket?</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://ericlippert.com/2013/05/17/quality-assurance-fail/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
	</channel>
</rss>
