C #: stack with two type elements

I want to create a stack with two different types

so I'm trying to write this down, but give an error:

Stack<[string,int]> S = new Stack<[string,int]>();
S.Push(["aaa",0]);

      

I've tried this before:

public class SItem{
    public string x;
    public int y;

    public SItem(string text,int index){
        this.x = text;
        this.y = index;
    }
}
Stack<SItem> S = new Stack<SItem>();
SItem Start = new SItem("aaa",0);
S.Push(Start);

      

but i want it to be very simple use like what i write before

any idea?

+3


source to share


3 answers


You might consider Tuple :

var stack = new Stack<Tuple<string, int>>();
stack.Push(Tuple.Create("string", 0));
var item = stack.Pop();

      



This removes the need to write your own class, and on the downside, as @AlexeiLevenkov commented, makes the code less readable.

+6


source


You can use KeyValuePair or Tuple (depending on your .Net version)



Stack<KeyValuePair<string, int>> stack = new Stack<KeyValuePair<string, int>>();
stack.Push(new KeyValuePair<string, int>("string", 5));

      

+2


source


Another way to do it is to use KeyValuePair :

Stack<KeyValuePair<string, int>> stack;

      

0


source







All Articles