You are on page 1of 2

GENERICS

Generics allow you to define type-safe data structures, without committing to actual data types. In
other words, generics allow you to write a class or method that can work with any data type.
Simple words, Generics are used to separate logic from data type.

Features of Generics?

Allows you to write code/use library methods which are type-safe, i.e. a List<string> is
guaranteed to be a list of strings.

As a result of generics being used the compiler can perform compile-time checks on code for
type safety, i.e. are you trying to put an int into that list of strings.

Faster than using objects as it either avoids boxing/unboxing (where .net has to convert value
types to reference types or vice-versa).
Allows you to write code which is applicable to many types with the same underlying
behaviour, i.e. a Dictionary<string, int> uses the same underlying code as a
Dictionary<DateTime, double>; using generics, the framework team only had to write one piece
of code to achieve both results with the above advantages too.

GENERIC CLASSES & METHODS.


Generic classes encapsulate operations that are not specific to a particular data type. Operations such as adding
and removing items from the collection are performed in basically the same way regardless of the type of data
being stored.

Example
// Declare the generic class.
public class GenericList<T>
{
void Add(T input) { }
}
class TestGenericList
{
private class ExampleClass { }
static void Main()
{

// Declare a list of type int.


GenericList<int> list1 = new GenericList<int>();

// Declare a list of type string.


GenericList<string> list2 = new GenericList<string>();

// Declare a list of type ExampleClass.


GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
}
}

GENERIC METHODS.
A generic method is a method that is declared with type parameters,

You might also like