Skip to main content

How to Use Queue and Stacks in C#? #RathrolaPremKumar

In this article we shall learn how to use Queue and Stacks in C#,

After reading this article, you will learn about
a)     Queue & Stack Introduction
b)    Using Queues
c)     Example on Queues
d)    Using Stacks
e)     Example on Stacks
Queue & Stack Introduction:
Queue objects and Stack objects are collection objects in the System.Collection namespace.
The Queue class tracks objects on First-in & First-Out basis.
The Stack class tracks objects on First-in & Last-out basis.
By using public methods of both Queue & Stacks classes, we can move objects to different locations.
Using Queues
There are two public methods in Queue class, description as below
a)     Enqueue –Queue: It add an object to end of the queue
b)    Dequeue –Queue: Removes and add the object at the beginning of Queue

Example on Queue:
Following example shows how to use Queue object to handle messages.
The messenger class In this code calls the sendMessage method to send messages in the sequence “One”,”Two”,”Three”.
class Messenger
    {
        static void Main(string[] args)
        {
            Buffer buf = new Buffer();
            buf.SendMessage(new Message("One"));
            buf.SendMessage(new Message("Two"));
            buf.ReceiveMessage();
            buf.SendMessage(new Message("Three"));
            buf.ReceiveMessage();
            buf.SendMessage(new Message("Four"));
            buf.ReceiveMessage();
            buf.ReceiveMessage();
        }
    }
The queue object places the messages in the buffer by the Enqueue method.
    class Buffer
    {
        private Queue messageBuffer;
        public void SendMessage(Message m)
        {
            messageBuffer.Enqueue(m);
            Console.WriteLine(m.ToString());
        }
        public Buffer()
        {
            messageBuffer = new Queue();
        }

    }




When it is ready to receive the messages, it write them to the console; in this case by calling Dequeue method.
        public void ReceiveMessage()
        {
            Message m = (Message)messageBuffer.Dequeue();
            Console.WriteLine(m.ToString());
        }

Queues Full Code:
using System;
using System.Collections;

namespace QueueAndStacks
{
    class Message
    {
        private string messageText;
        public Message(string s)
        {
            messageText = s;
        }
        public override string ToString()
        {
            return messageText;
        }
    }
    class Buffer
    {
        private Queue messageBuffer;
        public void SendMessage(Message m)
        {
            messageBuffer.Enqueue(m);
            Console.WriteLine(m.ToString());
        }
        public void ReceiveMessage()
        {
            Message m = (Message)messageBuffer.Dequeue();
            Console.WriteLine(m.ToString());
        }
        public Buffer()
        {
            messageBuffer = new Queue();
        }

    }

    class Messenger
    {
        static void Main(string[] args)
        {
            Buffer buf = new Buffer();
            buf.SendMessage(new Message("One"));
            buf.SendMessage(new Message("Two"));
            buf.ReceiveMessage();
            buf.SendMessage(new Message("Three"));
            buf.ReceiveMessage();
            buf.SendMessage(new Message("Four"));
            buf.ReceiveMessage();
            buf.ReceiveMessage();
        }
    }
}

Using Stacks
There are three types of public methods in stack class as described below
a)     Count: Gets the number of object contains in stack.
b)    Push: Insert an object at the top of the stack.
c)     Pop: Removes and returns the object at the top of stack
Examples:
Below code uses a stack object instead of a Queue object, note that messages are added by using Push and remove by using Pop.
Stacks Full code
using System;
using System.Collections;

namespace QueueAndStacks
{
    class Message
    {
        private string messageText;
        public Message(string s)
        {
            messageText = s;
        }
        public override string ToString()
        {
            return messageText;
        }
    }
    class Buffer
    {
        private Stack messageBuffer;
        public void SendMessage(Message m)
        {
            messageBuffer.Push(m);
            Console.WriteLine(m.ToString());
        }
        public void ReceiveMessage()
        {
            Message m = (Message)messageBuffer.Pop();
            Console.WriteLine(m.ToString());
        }
        public Buffer()
        {
            messageBuffer = new Stack();
        }

    }

    class Messenger
    {
        static void Main(string[] args)
        {
            Buffer buf = new Buffer();
            buf.SendMessage(new Message("One"));
            buf.SendMessage(new Message("Two"));
            buf.ReceiveMessage();
            buf.SendMessage(new Message("Three"));
            buf.ReceiveMessage();
            buf.SendMessage(new Message("Four"));
            buf.ReceiveMessage();
            buf.ReceiveMessage();
        }
    }
}

Thanks for reading my article, sharing is caring


Comments

Popular posts from this blog

ERROR: Cannot resolve the collation conflict between SQL_Latin1_General_CP1_CI_AS and Latin1_General_CI_AS_KS_WS in the equal to operation

ERROR: Cannot resolve the collation conflict between SQL_Latin1_General_CP1_CI_AS and Latin1_General_CI_AS_KS_WS in the equal to operation
dont get panic if u get the following error while in your joinings, there is a simple way to solve this.
it is because of collation settings on two columns we are doing joinings. it is because of collation settings on two columns we are doing joinings
First step is to figure out what are two colaltion that cause for conflicts. Let us assume that collation has not been set at the column level and instead at db level, then we have to execute two simple statements as below.

Statements: Select DATABASEPROPERTYYEX('DB1',N'Collation') Select DATABASEPROPERTYYEX('DB2',N'Collation')
One more thing, make a note that if you are on sharepoint you will get error as below
Latin_General_CI_AS_KS_WS. if you are on most any other database and use the dafault settings you may get this SQL_Latin_General_CP1_CI_AS.
Now we have to do some…

How To Create The Data Adapter Object Using ADO.NET by #RathrolaPremKumar

By reading this article, you will learn key points in ADO.NET, as given below. What is Data Adapter?Primary Data Adapters for the databases.Data Adapter properties.Methods used by Data Adapter.How to create Data Adapter with an example? Let’s start our demo with a Data Adapter introduction. Actually, we use Data Adapter object to establish the connection to the data source and manage the movement of date to and from the database. What is Data Adapter? A data adapter aobject serves as a bridge between a data set object and Data Source such as a database to retrieve and save the data. Data adapter contains a set of database commands and a database connection, which we use to fill a dataset object and update the Data Source. Primary data adapters for databases? .NET makes two primary data adapters available for use with the databases. Other data adapters can also be integrated with Visual Studio .NET. Primary Data Adapters are mentioned below. OleDbData Adapter, which is suitable for use wi…

Work 9 to 6 for Salary and 6 to 9 for Career

How much time one must spend in office, the subject line of the Post is something I have heard from a client several years back and believe the best of all choices. She was in executive rank and was highly successful in both office & home fronts.................................................................... She said following “Souvik, you get a salary to do 40 hours of work per week. You must come on time at 9 am and work efficiently to plan & finish it by 6 pm. Whatever you are doing during this time, you must try to do it in the best possible way. You should plan so that you do not sign up for more work than what you can deliver. Also manage your priorities & timing to avoid work fluctuations as much as practically possible.”  I nodded head as what she said is something everybody knows. She continued. “However, 9-6 work will only help you “earn” your salary. It will not be good enough to offer a sustained growth, especially in later part of your career. If you really w…