Collections in C#
C# includes varies classes that store the values or objects are called collections.
There are two types of collections available in C#:
- Non-generic collections
- Generic collections
The System.Collections namespace contains the non-generic collection types and System.Collections.Generic namespace includes generic collection types.
In most cases, it is recommended to use the generic collections because they perform faster than non-generic collections and also minimize exceptions by giving compile-time errors.
Non-generic Collections
- Arraylist
- Stack
- Queue
- Hashtable
Queue in C#
Create a Queue in C#
To create Queue<T> in C#, we need to use the System.Collection.Generic namespace.
Queue<dataType> queueName = new Queue<dataType>();Here, dataType indicates the queue's type. For example.
// create integer type stack
Queue<int> queue1 = new Queue<int>();
// create string type stack
Queue<string> queue2 = new Queue<string>();Example
using System;
using System.Collections.Generic;
class Program
{
public static void Main()
{
// create a queue
Queue<string> fruits = new Queue<string>();
// adds "Apple" and "Orange" to the queue
fruits.Enqueue("Apple");
fruits.Enqueue("Orange");
// print elements of the queue
foreach (string item in fruits)
{
Console.WriteLine(item);
}
}
}C# Queue Methods
C# provides 3 major Queue<T> methods. These methods are:
- Enqueue(): C#
using System; using System.Collections.Generic; class Program { public static void Main() { // create a queue Queue<int> numbers = new Queue<int>(); // adds 65 and 17 to the queue numbers.Enqueue(65); numbers.Enqueue(17); // print elements of the queue foreach (int item in numbers) { Console.WriteLine(item); } } }


Join the conversation! Your thoughts help the community grow.