Generics
C# 2.0 introduces new functionality named Generics. These allow us to create classes and methods decoupled from the data types. This means that using Generics we can create generalized classes and methods.
Generic classes are available in System.Collections.Generic namespace.
Example of generic methods
using
System;
using
System.Collections.Generic;
namespace
GenericsDemo
{
class Program
{
static void Main(string[]
args)
{
//Equal
method for numbers only
EqualNumber
objEqualNumber = new EqualNumber();
Console.WriteLine("Number Equals: " +
objEqualNumber.IsEqual(5, 6));
//Equal
method for string only
EqualString
objEqualString = new EqualString();
Console.WriteLine("String Equals: " +
objEqualString.IsEqual("Hello", "Hello"));
//Equal
method for both number and string using object parameter
//This
method use boxing and unboxing
EqualObject
objEqualObject = new EqualObject();
Console.WriteLine("Number Equals: " +
objEqualObject.IsEqual(10, 10));
Console.WriteLine("String Equals: " +
objEqualObject.IsEqual("Hello","Hello"));
//This
code will compile and execute successfully it is not type safety
Console.WriteLine("String Equals: " +
objEqualObject.IsEqual("Hello",
10));
//This
use Generics methods to compare equallity using strong type safety
//This
method dose not use boxing and unboxing
EqualGenerics
objEqualGenerics = new EqualGenerics();
Console.WriteLine("Number Equals: " +
objEqualGenerics.IsEqual<int>(10, 10));
Console.WriteLine("String Equals: " +
objEqualGenerics.IsEqual<string>("Hello","Hello"));
Console.ReadLine();
}
}
//objects
public class EqualObject
{
public bool IsEqual(object
value1, object value2)
{
return
value1.Equals(value2);
}
}
//number
public class EqualNumber
{
public bool IsEqual(int
value1, int value2)
{
return
value1.Equals(value2);
}
}
//string
public class EqualString
{
public bool IsEqual(string
value1, string value2)
{
return
value1.Equals(value2);
}
}
//Generics
public class EqualGenerics
{
public bool IsEqual<T>(T value1, T value2)
{
return
value1.Equals(value2);
}
}
}
Advantage of Generics
Use generic types to maximize code reuse, type safety, and
performance.
The most common use of generics is to create collection classes.
The .NET Framework class library contains several new generic
collection classes in the System.Collections.Generic namespace.
These should be used
whenever possible in place of classes such as ArrayList in the System.Collections namespace.
You can create your own generic interfaces, classes, methods,
events and delegates.
Generic classes may be constrained to enable access to methods
on particular data types. Information on the types used in a generic data type may be
obtained at run-time by means of reflection.