.Net framework 2.0 and above provides a concept of Generics, the namespace is System.Collections.Generic that contains some new generic based classes. Generic Classes and methods are useful for the reusability of the code and type safety which are not in other collection classes such as ArrayList. In this article we will discuss how can we use the Generics and what are the benefits of the Generic based code.
Generic can be fully user defined concept means user can create custom generic types and methods to provide the generalized design pattern with better efficiency and type safe.
However in the most cases we use the List
public class GenericListClass<T> { public void AddNode(T t) { // do } } public class TestClass { private class ExampleClass { } static void Main() { // Declare a list of type int. GenericListClass<int> objlist1 = new GenericListClass<int>(); objlist1.AddNode(5); // Declare a list of type string. GenericListClass<string> objlist2 = new GenericListClass<string>(); objlist2.AddNode("Sample"); // Declare a list of type ExampleClass. GenericList<ExampleClass> list3 = new GenericList<ExampleClass>(); } }
But when we have other System.Collections classes such as ArrayList and Array then why we use the generic class? or what is the different between generic class and other System.Collection Classes?. We have already said that the generic class and method has the capability of type-safe and reusability of the code.
type-safe
When we use the ArrayList class that stores an array of objects, and when we need to read the value from an ArrayList we need to explicitly cast it to the data type being stored in the specified location. See the following example:
See the below code:
System.Collections.ArrayList arrList = new System.Collections.ArrayList(); // Add an integer to the array list. arrList.Add(3); // Add a string to the array list. //This will compile, but may cause an error later. arrList.Add("Hi Welcome here");
Above arraylist contains integer and string type objects,this will cause an error when we add some code of lines. See this:
System.Collections.ArrayList arrList = new System.Collections.ArrayList(); // Add an integer to the arraylist. arrList.Add(3); // Add a string to the arraylist. //This will compile, but may cause an error later. arrList.Add("Hi Welcome here"); int Sum = 0; // This causes an InvalidCastException to be returned. foreach (int x in arrList) { Sum += x; }
The above code will consist the InvalidCasrException error when the Just-In-Time compiler try to cast the type string to integer. If we use the list<> for it, Than compile-time error will be exist.
List<int> list1 = new List<int>(); // No boxing, no casting: list1.Add(3); // Compile-time error: // list1.Add("Hi Welcome here");
Reusable
(continued…)