title: Unexpected operation order in Stack<T> related one liner
body: <p>By calling <code>Push()</code> and <code>Pop()</code> an instance of <code>Stack&lt;T&gt;</code> in a single line I get a different behavior than performing the imho same code in two lines.</p>
  
  <p>The following code snippet reproduces the behavior:</p>
  
  <pre><code>static void Main(string[] args)
  {
   Stack&lt;Element&gt; stack = new Stack&lt;Element&gt;();
   Element e1 = new Element { Value = "one" };
   Element e2 = new Element { Value = "two" };
   stack.Push(e1);
   stack.Push(e2);
  
   Expected(stack);  // element on satck has value "two"
   //Unexpected(stack);  // element on stack has value "one"
  
   Console.WriteLine(stack.Peek().Value);
   Console.ReadLine();
  }
  
  public static void Unexpected(Stack&lt;Element&gt; stack)
  {
   stack.Peek().Value = stack.Pop().Value;
  }
  
  public static void Expected(Stack&lt;Element&gt; stack)
  {
   Element e = stack.Pop();
   stack.Peek().Value = e.Value;
  }
  </code></pre>
  
  <p>The Element class is really basic:</p>
  
  <pre><code>public class Element
  {
   public string Value
   {
    get;
    set;
   }
  }
  </code></pre>
  
  <p>With this code I get the following result (.NET 3.5, Win 7, fully patched):</p>
  
  <ul>
  <li>Calling <code>Expected()</code> (version with
  two lines) leaves one element on the
  stack with <code>Value</code> set to <code>"two"</code>.</li>
  <li>When calling <code>Unexpected()</code> (Version
  with one line) I get one element on
  the stack with the <code>Value</code> set to
  <code>"one"</code>.</li>
  </ul>
  
  <p>The only reason for the difference I could imagine was the operator precedence. As the assignment operator (<code>=</code>) has the <a href="http://msdn.microsoft.com/en-us/library/aa691323%28VS.71%29.aspx" rel="nofollow noreferrer">lowest precedence</a> I see no reason why the two method should behave differently.</p>
  
  <p>I also had a look at the IL generated:</p>
  
  <pre><code>.method public hidebysig static void Unexpected(class [System]System.Collections.Generic.Stack`1&lt;class OperationOrder.Element&gt; stack) cil managed
  {
      .maxstack 8
      L_0000: ldarg.0 
      L_0001: callvirt instance !0 [System]System.Collections.Generic.Stack`1&lt;class OperationOrder.Element&gt;::Peek()
      L_0006: ldarg.0 
      L_0007: callvirt instance !0 [System]System.Collections.Generic.Stack`1&lt;class OperationOrder.Element&gt;::Pop()
      L_000c: callvirt instance string OperationOrder.Element::get_Value()
      L_0011: callvirt instance void OperationOrder.Element::set_Value(string)
      L_0016: ret 
  }
  </code></pre>
  
  <p>I'm not an IL crack, but for me this code still looks good ans should leave one element on the stack with value set to "two". </p>
  
  <p>Can anyone explain me the reason why the method <code>Unexpected()</code> does something different than <code>Expected()</code>?</p>
  
  <p>Thanks a lot!</p>
  
  <p>Lukas</p>