Generics provide a code template for creating type-safe code without referring to specific data types. They allow you to realize type safety at compile time. They allow you to create a data structure without committing to a specific data type. They allow you to delay the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.
It helps you to maximize code reuse, type safety, and performance.
Lets take an example of non-generic collection class like ArrayList, where we add integer values to the array list and perform addition operation on the list values.
using System.Collections;
namespace SampleTypeSafety
{
class SampleOperation
{
public static int Add()
{
ArrayList list = new ArrayList();
list.Add(6);
list.Add(9);
int result = 0;
foreach (int value in list)
{
result += value;
}
return result;
}
}
}
If we run above code then ot will return a value. But now add one more value to the ArrayList that the data type is float and perform the same Add operation.
using System.Collections;
namespace SampleTypeSafety
{
class SampleOperation
{
public static int Add()
{
ArrayList list = new ArrayList();
list.Add(6);
list.Add(9);
list.Add(6.9);
int result = 0;
foreach (int value in list)
{
result += value;
}
return result;
}
}
}
Now if we run above code then it will give an error (Specified cast is not valid). Because it contains both int and float values and while retrieving values we are type casting it to int.
Compared to above, Generics allow us to realize type safety at compile time. They allow us to create a data structure without committing to a specific data type.
using System.Collections.Generic;
namespace SampleTypeSafety
{
class SampleOperation
{
public static int Add()
{
List<int> list = new List<int>();
list.Add(5);
list.Add(9);
int result = 0;
foreach (int value in list)
{
result += value;
}
return result;
}
}
}
In the code above we define a list of type int. In other words, we can only add an integer value to the list and can't add a float value to it so when we retrieve values from the list using a foreach statement we only get an int value.
We can also reuse code using Generics :
using System.Collections.Generic;
namespace SampleReuse
{
class SampleOperation
{
public static void Swap<T>(ref T lhs, ref T rhs)
{
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}
}
}
Here we have used a generic class and declared a generic method with a type parameter. We can use the same method to swap values for different types. e.g. :
int a, b;
char c, d;
a = 10;
b = 20;
c = 'I';
d = 'V';
Swap<int>(ref a, ref b);
Swap<char>(ref c, ref d);
From Performance perspective, Generics give better performance as no boxing and unboxing is required.
No comments:
Post a Comment