-3

Possible Duplicate:
What is generics in C#?

What are the uses of generics and when can it be used?

Community
  • 1
  • 1
Even
  • 391
  • 3
  • 8
  • 17
  • What do know so far? Have you done any reading yet? Have a look here: http://msdn.microsoft.com/en-us/library/512aeb7t(v=vs.80).aspx then come back with more specific questions. – Nick Feb 25 '11 at 09:13
  • 1
    see also [What is a good C# generics tutorial?](http://stackoverflow.com/questions/467936/what-is-a-good-c-generics-tutorial) (btw both of these were listed among the *Related* posts on the right - next time please check more carefully before posting a duplicate question). – Péter Török Feb 25 '11 at 09:16

3 Answers3

1

There's an introduction to generics available on MSDN.

One of the simplest examples of the use of generics is a List<T>. What this means is that, if you wanted to have, in your program, a collection of something, say strings, you have a number of choices:

String[] anArrayOfStrings;
System.Collections.ArrayList anArrayListOfObject;
List<string> aListOfStrings;

Taking each in turn; anArrayOfStrings is an array of strings. That means that you can't add to it, or remove from it. It's fine if you have a fixed size number of items. anArrayListOfObject is the .net 1.0 "collection", with the downside that as it accepts object, you can put anything in there, not just strings.

The final option aListOfStrings is strongly typed in that the compiler will complain about any code which attempts to put something in that isn't a string. It makes your code more robust, readable (you don't have to write reams of code to ensure that what you put in/remove is a string) and flexible.

Rob
  • 45,296
  • 24
  • 122
  • 150
1

Generics is used to create "Type safe" collections like List, Map etc. It means that we can add only known/expected types to collections in order to avoid storing different data in one collection. For e.g

//without generics
ArrayList list = new ArrayList();
list.add(new Object());
list.add(new Interger());
list.add(new String());

//with generics 
ArrayList<String> list = new ArrayList<String>();
list.add(new Object()); //compile time error
list.add(new Interger()); //compile time error
list.add(new String()); //ok string its expected

As you can see from above code generics have been introduced to create type safe collections so that we wont get some unexpected type of object from collections at runtime.

Apart from collections we can also apply generics to methods and classes

Umesh K
  • 13,436
  • 25
  • 87
  • 129
0

Try to read C# in Depth. You will find great explanations of generics there.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Brijesh Mishra
  • 2,738
  • 1
  • 21
  • 36