32

I looked at some sample code using C# generics. Why and when should I use them?

All the examples were complex. I need a simple, clear example that gets me started with C# generics.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
  • 8
    See [this question](http://stackoverflow.com/questions/77632/what-is-cool-about-generics-why-use-them). –  Aug 31 '10 at 06:48
  • See: http://www.csharp-station.com/Tutorials/Lesson20.aspx – kenorb May 19 '15 at 12:55

4 Answers4

56

A very simple example is the generic List<T> class. It can hold a number of objects of any type. For example, you can declare a list of strings (new List<string>()) or a list of Animals (new List<Animal>()), because it is generic.

What if you couldn't use generics? You could use the ArrayList class, but the downside is that it's containing type is an object. So when you'd iterate over the list, you'd have to cast every item to its correct type (either string or Animal) which is more code and has a performance penalty. Plus, since an ArrayList holds objects, it isn't type-safe. You could still add an Animal to an ArrayList of strings:

ArrayList arrayList = new ArrayList();
arrayList.Add(new Animal());
arrayList.Add("");

So when iterating an ArrayList you'd have to check the type to make sure the instance is of a specific type, which results in poor code:

foreach (object o in arrayList)
{
  if(o is Animal)
    ((Animal)o).Speak();
}

With a generic List<string>, this is simply not possible:

List<string> stringList = new List<String>();
stringList.Add("Hello");
stringList.Add("Second String");
stringList.Add(new Animal()); // error! Animal cannot be cast to a string
Razzie
  • 30,441
  • 11
  • 62
  • 75
  • 2
    +1 for being able to give a nice, clean and non-complex example. Well done. – Subby Jan 23 '13 at 17:06
  • 2
    now that's what we call a basic explanation, with awesome examples, having real time code snippet. Great. +1 – Kings May 25 '15 at 10:15
  • Actually there is no difference in iterating an Arraylist/List syntactically. In fact your code for iterating an arraylist won't compile. Difference is in semantics, there is a [cast introduced for you by the foreach statement](http://ericlippert.com/2013/07/22/why-does-a-foreach-loop-silently-insert-an-explicit-conversion/). – Sriram Sakthivel Aug 26 '15 at 08:23
  • You are right @SriramSakthivel, that syntax was incorrect. Updated my answer – Razzie Mar 02 '18 at 14:06
7

To summarize other answers with some emphasis:

1) generics enable you to write 'generic' code (i.e., it will work for multiple types). If you have 'generic' behavior you want to write, which you need to behave for differing data types, you only need to write that code once. The example of List is a great example, you can need lists of perhaps customers, products, orders, suppliers...all using the same code instantiated for each type

//  snippet
List<Customer> customers = new List<Customer>();
Customer thisCustomer = new Customer();
customers.Add(thisCustomer);

List<Order> orders = new List<Order>();
Order thatOrder = new Order();
orders.Add(thatOrder);

//  etc.

2) amazingly, generics still enable type safety! So if you try this, you will rightly get an error:

//  continued for snippet above
Order anotherOrder = new Order();
customers.Add(anotherOrder);    //  FAIL!

And you would want that to be an error, so that later on your customer processing code doesn't have to handle a bogus order showing up in the customers list.

Jay
  • 10,058
  • 4
  • 26
  • 36
3

Duplication is the root of all evil. One case of code duplication occurs when you have to perform same operation on different types of data. Generics let you avoid it by allowing you to code around a 'generic' type and later substitute it with specific types.

The other solution to this problem is to use variables of type 'System.Object' to which object of any type can be assigned. This method involves boxing and unboxing operations between value and reference types which hit performance. Also type casting keeps the code from being clean.

Generics are supported in MSIL and the CLR which makes it perform really well.

You should read these articles about generics -

http://msdn.microsoft.com/en-us/library/512aeb7t(VS.80).aspx

http://msdn.microsoft.com/en-us/library/ms379564(VS.80).aspx#csharp_generics_topic1

Unmesh Kondolikar
  • 9,136
  • 3
  • 33
  • 51
0

In a nutshell, generics allow you to write classes that work with objects of any type, but without having to cast the data to Object. There are performance benefits for this, but it also makes your code more readable, maintainable, and less error-prone.

You should always use generics as opposed to the .NET 1.1 style classes when possible.

tylerl
  • 29,320
  • 12
  • 78
  • 110