TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Stack Collection

This C# Stack tutorial shows how to use this collection type. It uses Stack in simple loops.

Stack is a LIFO collection.

It provides a powerful and simple last-in-first-out data structure. This can help you develop parsers quickly and also replace complex recursive algorithms. Stack is a generic type.

Generic Class

Push. Usually the first action you need to do on Stack is Push elements into it. The word Push is a computer science term that means "add to the top." The example we see next returns a new Stack of integers from a method.

Then: It writes each value of the stack to the Console in a foreach-loop with Console.WriteLine.

Console.WriteLine

C# program that creates new Stack of integers

using System;
using System.Collections.Generic;

class Program
{
    static Stack<int> GetStack()
    {
	Stack<int> stack = new Stack<int>();
	stack.Push(100);
	stack.Push(1000);
	stack.Push(10000);
	return stack;
    }

    static void Main()
    {
	var stack = GetStack();
	Console.WriteLine("--- Stack contents ---");
	foreach (int i in stack)
	{
	    Console.WriteLine(i);
	}
    }
}

Output

--- Stack contents ---
10000
1000
100

In this program, the stack local variable is assigned to a new Stack containing three integers. The ints were added with the 10000 last. Next in Main the values are printed out to the Console.

Tip: You can see that 10000 is displayed first. This is explained by the LIFO concept—last in first out.

LIFO: The last element added (with Push) to Stack is the first one removed (with Pop).

Pop. Here we see the Pop method on Stack, and also the Peek method. When you call Pop, the elements from the top of the Stack is returned, and the element is removed from the collection.

Next: This example uses the same Stack collection as above, which means Pop returns 10000.

Also: It uses Peek, which does the same thing as Pop but does not remove the element.

C# program that uses Pop method on Stack

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	// Get the stack [See above definition of this method]
	Stack<int> stack = GetStack();

	// Pop the top element
	int pop = stack.Pop();

	// Write to the console
	Console.WriteLine("--- Element popped from top of Stack ---");
	Console.WriteLine(pop);

	// Now look at the top element
	int peek = stack.Peek();
	Console.WriteLine("--- Element now at the top ---");
	Console.WriteLine(peek);
    }
}

Output
    (These were the LAST elements added; see the GetStack method)

--- Element popped from top of Stack ---
10000
--- Element now at the top ---
1000

Pop and Peek both act on the top of Stack, meaning the element most recently added. They also both return that top value. But Peek does not remove the element from the Stack collection. It only gets the value—it "peeks" at the value.

And: Pop removes the reference. If you call Pop, then afterwards Peek and Pop will return the next value when they are called.

Clear, count. You can use Clear and Count on your Stack. These methods won't raise exceptions unless your Stack reference is null. The Count property is used without parenthesis, while Clear() is a parameterless method.

Note: The example receives the Stack used in the above examples, then counts it, clears it, and finally counts it again.

C# program that uses Clear and Count methods

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	// Get the stack [See method definition above]
	Stack<int> stack = GetStack();

	// Count the number of elements in the Stack
	int count = stack.Count;
	Console.WriteLine("--- Element count ---");
	Console.WriteLine(count);

	// Clear the Stack
	stack.Clear();
	Console.WriteLine("--- Stack was cleared ---");
	Console.WriteLine(stack.Count);
    }
}

Output

--- Element count ---
3
--- Stack was cleared ---
0

Using null stacks. First, the value null is allowed in Stacks with reference types such as string. You can also assign your Stack to null instead of calling Clear. This changes slightly the performance characteristics.

Null

Performance: When assigning to null, the contents are not changed. Instead the reference is unrooted in the garbage collector.

Exceptions. You will probably encounter exceptions the first time you use Stack. When you call Pop or Peek on your Stack, the runtime will throw an exception if the Stack has zero elements. This is easily solved.

To work around this problem, you must check the Count property. The next example shows how to catch the exception raised by this situation, and then shows the right way to deal with it.

InvalidOperationException

C# program that uses Stack incorrectly, correctly

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	// Create an empty Stack.
	var stack = new Stack<int>();

	try
	{
	    // This throws an exception.
	    int pop = stack.Pop();
	}
	catch (Exception ex)
	{
	    Console.WriteLine("--- Exception raised by Pop ---");
	    Console.WriteLine(ex.ToString());
	}

	// Here we safely Pop the stack.
	if (stack.Count > 0)
	{
	    int safe = stack.Pop();
	}
	else
	{
	    Console.WriteLine("--- Avoided exception by using Count method ---");
	}
    }
}

Output

--- Exception raised by Pop ---
System.InvalidOperationException: Stack empty.
    ...
    ...
--- Avoided exception by using Count method

Copy, search. You can use different constructors of Stack to streamline your code. One constructor accepts an IEnumerable parameter, which is an interface that most collections implement. Here we use that constructor.

Constructor

Also: We search the Stack with the Contains method. The Contains method on Stack returns true if the element is found.

True and False

C# program that uses the Stack constructor

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
	// An example string array.
	string[] values = { "Dot", "Net", "Perls" };

	// Copy an array into a Stack.
	var stack = new Stack<string>(values);

	// Display the Stack.
	Console.WriteLine("--- Stack contents ---");
	foreach (string value in stack)
	{
	    Console.WriteLine(value);
	}

	// See if the stack contains "Perls"
	Console.WriteLine("--- Stack Contains method result ---");
	bool contains = stack.Contains("Perls");
	Console.WriteLine(contains);
    }
}

Output

--- Stack contents ---
Perls
Net
Dot
--- Stack Contains method result ---
True

In this example, the Stack generic collection searches the elements with Contains by using the interface defined in the collection. The object reference is not compared. Instead the string contents are.

Discussion. There are several other methods on Stack in System.Collections.Generic. You can copy your Stack to a new array with ToArray(). Also, you can use TrimExcess if your Stack is using too much memory.

Arrays

Internally: TrimExcess will check the Stack's fill rate, and then resize the internal array.

When looking inside Stack with IL Disassembler, we see it is implemented with an array of type T[]. This is type you specify in the declaration. Stack is basically a wrapper around an array. No boxing or unboxing will occur.

IL Disassembler

Also, I have used Stack for developing simple parsers, such as HTML parsers and validators. Many parsers push new elements they encounter, and then when they exit the element, they pop elements. This makes it easy to validate HTML.

Research. Stacks are well-researched in computer science literature. Method calls are stored within stacks. A pushdown stack is an abstract type that we can use in programs to push and pop elements.

A pushdown stack is an abstract data type that comprises two basic operations: insert (push) a new item, and remove (pop) the item that was most recently inserted.

Algorithms in C++

Summary. We saw examples of how you can use Stack(T). The Stack collection, found in the System.Collections.Generic namespace, provides a simple wrapper on an array. Stack is a useful abstraction of the classic stack data structure.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf