Enter your email address:


feedburner count

C# 2.0 Generics

Labels:

Generics Overview

  • Use generic types to maximize code reuse, type safety, and performance.

  • The most common use of generics is to create collection classes.

  • The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. These should be used whenever possible in place of classes such as ArrayList in the System.Collections namespace.

  • You can create your own generic interfaces, classes, methods, events and delegates.

  • Generic classes may be constrained to enable access to methods on particular data types.

Why Generics ?

Type safety casting & performance:

Using generics is not only safer than general old collection class (such as ArrayList, Collections...) but also significantly faster.

C# 1.1 :
ArrayList customers = new ArrayList();
Customer customer
= new Customer();

// Boxing --> descrease performance. No type-checking
customers.Add(customer);
// Boxing --> descrease performance. No type-checking
customers.Add("Some string");

// throw exception
// Customer customer = customers[0];

C# 2.0 :

List<Customer> customers = new List<Customers>();
Customer customer
= new Customer();

// No Boxing, no casting --> increase performance.
customers.Add(customer);

// Type-Checking : Compile-time error
customers.Add("Some string");

// No UnBoxing, no casting --> increase performance .
// Not throw exception

Customer customer2 = customers[0];

// UnBoxing --> decrease performance
Customer customer2 = (customer)customers[0];




blog comments powered by Disqus