These are the extension to collections. These store specific types and
provides type safety. We need to explicitly specify the type here and these are called strongly
typed as these don’t get any run time issues as typecast not required while reading.
Stack, Queue, SortedList, LinkedList, Dictionaryare comes under generic
collections.
List: The List is the same as ArrayList but takes a specific type of collection that is defined at the list
declaration.
For Example List takes only int type of data as collection and List takes
only string collections. So while reading we can read with that type as int or string respectively
instead of using an object and typecasting.
Dictionary: The Dictionary is the same as Hashtable, where we specify the key and value but
here it stores the key and values of only that type defined at dictionary during declaration.
These keys help in accessing the values.
For Example Dictionary stores key of type int only and values of string only. So while
fetching the dictionary values the index of int values helps here.
Example 5: It shows the Stack, Queue, List, and Dictionary usage in generic collections.
using System;
namespace SampleProgram {
class MySample {
public static void Main(string[] args) {
//Stack
Stack <
int >
st = new Stack <
int >
();
st.Push(100);
st.Push(120);
st.Push(140);
st.Push(135);
Console.WriteLine( " Stack data ");
foreach(int m in st) {
Console.Write($ "{
m
} ");
}
Console.WriteLine();
Console.WriteLine($ " Last Element is: {
st.Peek()
} ");
st.Pop();
foreach(int m in st) {
Console.Write($ " {
m
} ");
}
Console.WriteLine();
//Queue
Queue <
double >
qu = new Queue <
double >
();
qu.Enqueue(108);
qu.Enqueue(12.45);
qu.Enqueue(234.8);
qu.Enqueue(23.5);
Console.WriteLine( " Queue data ");
foreach(double m in qu) {
Console.Write($ " {
m
} ");
}
Console.WriteLine();
qu.Dequeue();
foreach(double m in qu) {
Console.Write($ " {
m
} ");
}
Console.WriteLine();
//List
List <
int >
myInts = new List <
int >
();
myInts.Add(1);
myInts.Add(2);
myInts.Add(3);
Console.WriteLine( " List data ");
for (int i = 0; i Console.Write( " {
0
} ", myInts[i]);
}
Console.WriteLine();
//Dictionary
Dictionary <
int,
string >
customers = new Dictionary <
int,
string >
();
customers.Add(100, " America ");
customers.Add(101, " Mexico ");
customers.Add(103, "London ");
Console.WriteLine( " Dictionary data ");
foreach(KeyValuePair " int, string " custKeyVal in customers) {
Console.WriteLine( " Customer ID: {
0
},
Name: {
1
} ", custKeyVal.Key, custKeyVal.Value);
}
Console.ReadKey();
}
}
}
The output will be:
Stack data
135 140 120 100
Last Element is: 135
140 120 100
Queue data
108 12.45 234.8 23.5
12.45 234.8 23.5
List data
1 2 3
Dictionary data
Customer ID: 100, Name: America
Customer ID: 101, Name: Mexico
Customer ID: 103, Name: London