Generics in C# allows a programmer to generate a class or method which can work with multiple datatypes.
The specification of datatype of the elements used in class or methods is delayed by using Generics until these elements are actually used.
The generic class or generic method is defined with datatypes substitutes, these substitutes are replaced with specific datatype whenever generic class object is created or whenever generic method is called thus specific type of code is generated by the compiler when substitute is replaced by datatype.
Example to demonstrate Generics in C# :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GenericDemo
{
public class GenericArray<A>
{
private A[] arr;
public GenericArray(int n)
{
arr = new A[n + 1];
}
public A getItem(int index)
{
return arr[index];
}
public void setItem(int index, A value)
{
arr[index] = value;
}
}
class GenericTesting
{
static void Main(string[] args)
{
//int array as dataype substitute
GenericArray<int> integer_Array = new GenericArray<int>(5);
for (int i = 0; i < 5; i++)
integer_Array.setItem(i, i * 9);
for (int i = 0; i < 5; i++)
Console.Write(integer_Array.getItem(i) + " ");
Console.WriteLine();
//character array as dataype substitute
GenericArray<char> characterArray = new GenericArray<char>(5);
for (int i = 0; i < 5; i++)
characterArray.setItem(i, (char)(i + 65));
for (int i = 0; i < 5; i++)
Console.Write(characterArray.getItem(i) + " ");
Console.WriteLine();
Console.ReadKey();
}
}
}
Output:
0 9 18 27 36
A B C D E
Features of Generics:
Generic collection classes are contained in System.Collections.Generic namespace.
Interfaces,classes,events,methods,delegates can be made generic according to requirement.
Generics provides maximum code reusability, enhances performance and type security.
By using reflection information of the type used in generic data type can be obtained at run time.
0 Comment(s)