Home

C# Collections: The .NET Framework Built-In Stack Collection Class

     

Introduction

To support stack types of collections, the .NET Framework provides the Stack class. Stack is a serializable class that implements the ICollection (giving the ability to know the number of items in the list) and the IEnumerable (which gives the ability to use foreach).

 

Creating a Stack

The Stack class is equipped with three constructors. The default constructor allows you to create a stack without primarily taking any action. Here is an example:

using System;
using System.Collections;

[Serializable]
public class Sport
{
    public string Name;
    public uint PlayersPerTeam;
}

public static class Program
{
    public static int  Main(string[] args)
    {
        Stack players = new Stack();

        return 0;
    }
}

If you create a stack with this constructor, the list is primarily empty with a default capacity. If you want, before initializing the list, you can specify how much space the compiler should primarily allocate for the number of eventual items of the list. To provide this information, the Stack class is equipped with the following constructor:

public Stack(int initialCapacity);

Adding Items to a Stack

To add an item to a stack, you can call the Push() method of the Stack class. Its syntax is:

public virtual void Push(object obj);

The new item is passed as argument to the method. Here is an example:

using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class Sport
{
    public string Name;
    public uint PlayersPerTeam;
}

public static class Program
{
    public static int  Main(string[] args)
    {
        Stack players = new Stack();
        Sport basketball = new Sport();

        basketball.Name = "Basketball";
        basketball.PlayersPerTeam = 5;
        players.Push(basketball);

        SaveSports(players);
        return 0;
    }

    public static void SaveSports(Stack stc)
    {
        FileStream fsSport = new FileStream("Sports.spt",
                                            FileMode.Create,
                                            FileAccess.Write);
        BinaryFormatter bfSport = new BinaryFormatter();

        bfSport.Serialize(fsSport, stc);
        fsSport.Close();
    }
}

Whenever you add a new item to the stack, the compiler increases the number of items in the list. This number is stored in the Count property of the Stack class.

If you have a series of items that were created using a class that implements the ICollection interface, you can use the following constructor of the Stack class:

public Stack(ICollection col);

 When using this constructor, pass a variable of collection class as argument. Here is an example:

using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class Sport
{
    public string Name;
    public uint PlayersPerTeam;
}

public static class Program
{
    public static int  Main(string[] args)
    {
        Sport spt = new Sport();
        ArrayList lstSports = new ArrayList();

        spt.Name = "Volleyball";
        spt.PlayersPerTeam = 6;
        lstSports.Add(spt);

        spt = new Sport();
        spt.Name = "Tennis Single";
        spt.PlayersPerTeam = 1;
        lstSports.Add(spt);

        spt = new Sport();
        spt.Name = "Handball";
        spt.PlayersPerTeam = 6;
        lstSports.Add(spt);

        Stack sports = new Stack(lstSports);

        SaveSports(sports);
        return 0;
    }

    public static void SaveSports(Stack stc)
    {
        FileStream fsSport = new FileStream("Sports.spt",
                                            FileMode.Create,
                                            FileAccess.Write);
        BinaryFormatter bfSport = new BinaryFormatter();

        bfSport.Serialize(fsSport, stc);
        fsSport.Close();
    }
}

Accessing an Item in the Stack

As mentioned previously, the Stack class overrides the GetEnumerator() method by implementing the IEnumerable interface. This allows you to access each member of the stack using the foreach loop. Here is an example:

using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class Sport
{
    public string Name;
    public uint PlayersPerTeam;
}

public static class Program
{
    public static int  Main(string[] args)
    {
        Stack sports = OpenSports();

        foreach (Sport spt in sports)
        {
            Console.WriteLine("=-+-+-+-+-= Sport =-+-+-+-+-=");
            Console.WriteLine("Sport Name:   {0}", spt.Name);
            Console.WriteLine("Players/Team: {0}", spt.PlayersPerTeam);
        }

        Console.WriteLine();
        return 0;
    }

    public static void SaveSports(Stack stc)
    {
        FileStream fsSport = new FileStream("Sports.spt",
                                            FileMode.Create,
                                            FileAccess.Write);
        BinaryFormatter bfSport = new BinaryFormatter();

        bfSport.Serialize(fsSport, stc);
        fsSport.Close();
    }

    public static Stack OpenSports()
    {
        FileStream fsSport = new FileStream("Sports.spt",
                                            FileMode.Open,
                                            FileAccess.Read);
        BinaryFormatter bfSport = new BinaryFormatter();

        Stack games = (Stack)bfSport.Deserialize(fsSport);
        fsSport.Close();

        return games;
    }
}

To find out if the list contains a particular item, you can call the Contains() method of the Stack class. Its syntax is:

public virtual bool Contains(object obj);

Removing Items From a Stack

As mentioned earlier, a stack is organized so that the last item that was added to the list is the first one to be removed. To support this operation, the Stack class is equipped with the Pop() method. Its syntax is:

public virtual object Pop();

When called, this method removed the last item in the stack. If you are interested to know what item was removed, this method returns it as an Object value.

Here is an example of calling the method:

using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization.Formatters.Binary;

[Serializable]
public class Sport
{
    public string Name;
    public uint PlayersPerTeam;
}

public static class Program
{
    public static int  Main(string[] args)
    {
        Stack sports = OpenSports();

        foreach (Sport spt in sports)
        {
            Console.WriteLine("=-+-+-+-+-= Sport =-+-+-+-+-=");
            Console.WriteLine("Sport Name:   {0}", spt.Name);
            Console.WriteLine("Players/Team: {0}", spt.PlayersPerTeam);
        }

        Sport  one = (Sport)sports.Pop();

        Console.WriteLine("The sport removed was");
        Console.WriteLine("=-+-+-+-+-= Sport =-+-+-+-+-=");
        Console.WriteLine("Sport Name:   {0}", one.Name);
        Console.WriteLine("Players/Team: {0}", one.PlayersPerTeam);

        SaveSports(sports);
        sports = OpenSports();

        Console.WriteLine("=====================================");
        foreach (Sport spt in sports)
        {
            Console.WriteLine("Sport Name:   {0}", spt.Name);
            Console.WriteLine("Players/Team: {0}", spt.PlayersPerTeam);
            Console.WriteLine("=-+-+-+-+-= Sport =-+-+-+-+-=");
        }
        
        Console.WriteLine();
        return 0;
    }

    public static void SaveSports(Stack stc)
    {
        FileStream fsSport = new FileStream("Sports.spt",
                                            FileMode.Create,
                                            FileAccess.Write);
        BinaryFormatter bfSport = new BinaryFormatter();

        bfSport.Serialize(fsSport, stc);
        fsSport.Close();
    }

    public static Stack OpenSports()
    {
        FileStream fsSport = new FileStream("Sports.spt",
                                            FileMode.Open,
                                            FileAccess.Read);
        BinaryFormatter bfSport = new BinaryFormatter();

        Stack games = (Stack)bfSport.Deserialize(fsSport);
        fsSport.Close();

        return games;
    }
}

The Pop() method is used to remove one item from the stack. To remove all items from the list, you can call the Clear() method whose syntax is:

public virtual void Clear();
 
 

Home Copyright © 2010-2016, FunctionX