Unexpected workflow in Stack <T> associated with a single layer

Causing Push()and Pop()a copy of Stack<T>a single line, I get a different behavior than doing imho one code in two lines.

The following code snippet reproduces the behavior:

static void Main(string[] args)
{
 Stack<Element> stack = new Stack<Element>();
 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<Element> stack)
{
 stack.Peek().Value = stack.Pop().Value;
}

public static void Expected(Stack<Element> stack)
{
 Element e = stack.Pop();
 stack.Peek().Value = e.Value;
}

The Element class is really basic:

public class Element
{
 public string Value
 {
  get;
  set;
 }
}

With this code, I get the following result (.NET 3.5, Win 7, fully fixed):

  • The call Expected()(version with two lines) leaves one item on the stack with Valueset to "two".
  • When called Unexpected()(single-line version) I get one item on the stack with Valueset to "one".

, , - . (=) , , -.

IL:

.method public hidebysig static void Unexpected(class [System]System.Collections.Generic.Stack`1<class OperationOrder.Element> stack) cil managed
{
    .maxstack 8
    L_0000: ldarg.0 
    L_0001: callvirt instance !0 [System]System.Collections.Generic.Stack`1<class OperationOrder.Element>::Peek()
    L_0006: ldarg.0 
    L_0007: callvirt instance !0 [System]System.Collections.Generic.Stack`1<class OperationOrder.Element>::Pop()
    L_000c: callvirt instance string OperationOrder.Element::get_Value()
    L_0011: callvirt instance void OperationOrder.Element::set_Value(string)
    L_0016: ret 
}

IL, - , , "".

- , Unexpected() , Expected()?

!

+5
2

stack.Peek().set_Value(stack.Pop().Value);

.

EDIT. , .

+5

# . . = . "" Pop() , Peek(). "" Peek() Pop(), .

SLaks , . - ! SLaks , , . , Value - ; , , .

"", , , , , - . . . . .

, F() + G() * H(). * , +. , G(), H(), , F(), .

. : . , F(), G(), H(). G() H(). F(). , :

temp1 = F();
temp2 = G();
temp3 = H();
temp4 = temp2 * temp3;
result = temp1 + temp4;

= , ; , . , , - - , . . . .

?

: , ; , , . # , ; , , , :

http://blogs.msdn.com/ericlippert/archive/tags/precedence/default.aspx

+9

All Articles