Generics

The need to create class that can work with any type of data is increasing. Generics allow you to define type-safe data structures, without committing to actual data types. By using Generics, you get to reuse data processing algorithms without duplicating type-specific code.

Generics, when compared to inheritance, can increase type safety and reduce casting and boxing.

Generic Types

A generic type declares type parameters to be filled in by the consumer of the generic type, which supplies the type arguments.

An example of generic type is the List<T> that you can found in the namespace System.Collections.Generic. This list is designed to stack instances of type T.

We can user List<T> as follows:

List<string> list = new List<string>();

list.Add("Johnny");
list.Add("Zraiby");

string firstName = list[0];
string lastName = list[1];

Notice that no downcasts are required in the last two lines, avoiding the possibility of runtime error and eliminating the overhead of boxing/unboxing.

Generic Methods

A generic method declares type parameters within the signature of a method.

static T Add<T> (T a, T b)
{
      return a + b;
}

Add<T> can be used as follows:

int x = 5;
int y = 10;
int result = Add<int> (x, y);
decimal x = 5.23;
decimal y = 10.23;
decimal result = Add<decimal> (x, y);

Declaring Type Parameters

Type parameters can be introduced in the declaration of classes, structs, interfaces, delegates and methods. A generic type or methods can have multiple parameters.

void Concatinat<T1, T2, T3>(T1 x, T2 y, T3 z);

To use this method:

string x = "johnny";
int y = 12;
decimal z = 10.34;
Concatinat<string, int, decimal>(x, y, z);

You can overload the same generic methods or generic types as long as the number of type parameters differs:

void Concatinat<T1, T2>(T1 x, T2 y);
void Concatinat<T1, T2, T3>(T1 x, T2 y, T3 z);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s