Generics

Generics

Generics is a form of abstraction in developing code. Instead of writing a function or a class for a particular type, it can be written generally to use any type. When an instance of the generic class is instantiated, the type is specified.

Generics was introduced in .NET Framework 2.0. MS recommends using Generics functions and classes instead of non-generic.

Generic namespace is under the System.Collections.

Example:

Say you want to swap two integers, strings etc.
In the non-generic form, you would create 2 seperate functions, one for Integers and one for Strings.. to eliminate this duplication for the same functionality, we can use the generic methods and classes.

public void Swap( a, b)
{ T temp;
temp=a;
a=b;
b=temp;
}

We can call the above generic function for either int or string.
Swap(int a, int b);
Swap(string s1, string s2);

How do you set default values ???

C# provides a keyword called "default" which
1) for value types, the default value is 0.2) for reference types, the default value is null.3) for reference fields in structs(value type), the default value is null.
For example: after swapping the 2 values, you would like to set the temp value to a default value depending on the type.

public void Swap( a, b)
{
T temp;
temp=a;
a=b;
b=temp;
// Default(int)Temp = 0
//Default(string) temp=null;
temp=default(T);
}


This is just a basic introduction. Shall introduce more uses and detail about generics later.

Comments

Popular posts from this blog

Knowing too much is bad(in the world of OOP)

Reverse a LinkedList Algorithm

DateTime.Now in C#