Ignora collegamentiHome / Blog

Blog


How to use Stack in C#

This simple example shows how to use Stack in C#.

using System;
using System.Collections;

class StackTest
{   
	public static void Main()   
	{   
		// Create a stack of Person,  	
		// Simple collection LIFO (Last-In, First-Out) objects of type Person
		Stack personStack = new Stack();
		
		// "Push" some "Person" in the Stack
		personStack.Push(new Person("Barbara", "Denver", 34));
		personStack.Push(new Person("Sofia", "Brucks", 32));
		personStack.Push(new Person("Elena", "Silver", 31));
		personStack.Push(new Person("Asia", "Solis", 38));
		personStack.Push(new Person("Paris", "Jordan", 25));
		
		// Prints some informations of the Stack
		Console.WriteLine();
		Console.WriteLine("The Stack contains " + personStack.Count + " elements" );
		Console.WriteLine("The element that is located at the top of the Stack is: " + personStack.Peek());

		// Prints the contents of the Stack
		Console.WriteLine();
		Console.WriteLine("Stack contains the following elements:");
		foreach(Person p in personStack)
		{
			Console.WriteLine(p.ToString());
		}
		
		// Pop some elements from the Stack
		personStack.Pop();
		personStack.Pop();
		personStack.Pop();
		
		// Prints the contents of the Stack
		Console.WriteLine();
		Console.WriteLine("After 3 Pop(), Stack contains the following elements:");
		foreach(Person p in personStack)
		{
			Console.WriteLine(p.ToString());
		}
	}
}

/// <summary>
/// A typical sample class for objects of type Person
/// This class implements the interface IComparable
/// </summary>
class Person : IComparable
{
	string name;
	string surname;
	byte age;
	
	public Person()
	{}
	
	public Person(string n, string s, byte a)
	{
	name = n;
	surname = s;
	age = a;
	}
	
	public override string ToString()
	{
		return name+ ", " + surname + ", (" + age + ")";
	}
	
	public int CompareTo(object obj)
	{
        if(obj is Person) {
            Person p = (Person) obj;
            return age.CompareTo(p.age);
        }
        throw new ArgumentException("object is not a Person");    
    }
}

This is the output of the program:

The Stack contains 5 elements
The element that is located at the top of the Stack is: Paris, Jordan, (25)

Stack contains the following elements:
Paris, Jordan, (25)
Asia, Solis, (38)
Elena, Silver, (31)
Sofia, Brucks, (32)
Barbara, Denver, (34)

After 3 Pop(), Stack contains the following elements:
Sofia, Brucks, (32)
Barbara, Denver, (34)



Category: C#