Sign in to follow this  
mounty0

Basic C# query

Recommended Posts

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 this post


Link to post
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 this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this