# Basic C# query

## Recommended Posts

mounty0    132
Recently I've been learning C#, but I'm stuck trying to figure out how to manipulate an individual object on a stack, from the code below:
public class MyObj
{
private int val;

public MyObj(int v)
{
Val = v;
}

public int Val
{
get { return val;  }
set { val = value; }
}
}

class MainApp
{
public static void Main()
{
testStack();
}

public static void testStack()
{
System.Collections.Stack stack = new System.Collections.Stack();

stack.Push(new MyObj(1));
stack.Push(new MyObj(10));

//stack[0].Val = 2;	//--> ?
}
}


How can I go about accessing and changing the Val variable in stack[0]? as the line doesn't compile at all. I've been searching all over but the examples I found used arrays which do allow subscripts such as this, but not stacks? thanks! mounty

##### Share on other sites
You don't. A stack is not meant for use in that way. You only want to perform operations on the top of the stack if you want to use a stack. Otherwise, use some other container (a List<T> -- which, incidentally, isn't a linked list -- is a pretty decent one to use as a de facto container).

##### Share on other sites
mounty0    132
ah ok didn't realise they work different, thanks for the info!