Enter your email address:


feedburner count

C# 2.0 : Generic methods

Labels:

This is a typical non-generic method :

void AddMultiple(List<Customer> customers, params Customer[] values)
{
foreach (Customer value in values)
{
customers.Add(value);
}
}

In order to add mutiple customer into List :

List<Customer> customers = new List<Customer>();
AddMultiple(customers,
new Customer(),
new
Customer(), new Customer());

However, the method above only works with type . To have it work
with any List , the method must be written as a generic method.
A generic method has one or more type parameters specified in <
and > delimiters after the method name :

void AddMultiple<T>(List<T> customList, params T[] values)
{
foreach (T value in values)
{
customList.Add(value);
}
}

Finally, we can add any type to generic List :

List<int> listInteger = new List<int>();
AddMultiple
<int>(listInteger, 1, 2, 3, 4);

List
<Customer> customers = new List<Customer>;
AddMultiple
<Customer>(customers,
new
Customer(),
new Customer(),
new Customer(),
new Customer());

In the example above, since the first regular argument is type List
listInteger, and the subsequent arguments are of type int 1, 2, 3 ,
4
the compiler can reason that the type parameter must be int. Thus,
we can use shorter syntax without specifying the type parameter
(<int>) :
List<int> listInteger = new List<int>();
AddMultiple(listInteger,
1, 2, 3, 4);

The same for the second scenario :

List<Customer> customers = new List<Customer>();
AddMultiple(customers,
new Customer(),
new Customer(),
new Customer(),
new
Customer());




blog comments powered by Disqus