Before explaining Generics lets take up an example of ArrayList.
ArrayList
using System.Collections;
int intTotal = 0;
ArrayList alMarks = new ArrayList();
private void btnTotal_Click(object sender, EventArgs e)
{
alMarks.Add(98);
alMarks.Add(99);
alMarks.Add(89);
//alMarks.Add("Shalvin");
foreach (int i in alMarks)
intTotal += i;
MessageBox.Show(intTotal.ToString());
}
'VB .Net
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim intTotal As Integer = 0
Dim alMarks As New ArrayList()
alMarks.Add(98)
alMarks.Add(99)
alMarks.Add(89)
For Each i As Integer In alMarks
intTotal += i
Next
MessageBox.Show(intTotal.ToString())
End Sub
It works perfectly fine. Nothing prevents you from giving a string value to array list as shown in the commented line in the code. Because an arraylist accepts parameter of type object. But when you run the application you will receive a runtime error.
Generics
Framework 2.0 introduced generic collection which as type safe collections.
List<int> intMarks = new List<int>();
private void Form1_Load(object sender, EventArgs e)
{
intMarks.Add(98);
intMarks.Add(90);
intMarks.Add(99);
int sum = 0;
foreach (int i in intMarks)
sum += i;
MessageBox.Show(sum.ToString());
}
VB.Net
Dim intMarks As New List(Of Integer)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
intMarks.Add(98)
intMarks.Add(90)
intMarks.Add(99)
Dim sum As Integer = 0
For Each i As Integer In intMarks
sum += i
Next
MessageBox.Show(sum.ToString())
End Sub
Now if you try to give a string value to the the generic list you will get a compiler error which proves the fact that generics are type safe.
C# 3.0 Collection Initializer
With C# 3.0 it is possible to initialize a list as follows:
which is undoubtedly a great code saver.
Generic List of Custom Class
class Session
{
public string Speaker { get; set; }
public string SessionName { get; set; }
}
List<Session> glSessions = new List<Session>{
new Session{Speaker = "Shalvin P D", SessionName= "Entity Framework 4"},
new Session{Speaker="Praseed Pai", SessionName="Powershell"}};
dataGrid1.ItemsSource = glSessions;
Related Blog
Linq to Objects
Hashtable and DictionaryEntry ReadOnlyCollectionBase Class