Possible Duplicate:
What is generics in C#?
What are the uses of generics and when can it be used?
Possible Duplicate:
What is generics in C#?
What are the uses of generics and when can it be used?
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.
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
Try to read C# in Depth. You will find great explanations of generics there.