| Shalvin.Com Home |
|
Generics Before explaining Generics lets take up an example of 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()); } 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. Framework 2.0 introduced generic collection which as type safe collections. //Creating a generic list object List int intTotal = 0; private void Form1_Load(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()); } Now if you try to give a string value to the the generic list you will get a compiler error which prooves the fact that generics are type safe. |