What are generics, its use and application?

Possible duplicate:
What are generics in C #?

What is the use of generics and when can they be used?

-3
source share
3 answers

Generics is used to create collections of type "safe type", such as "List", "Map", etc. This means that we can only add known / expected types to collections to avoid storing different data in the same collection. For instance,

//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 the above code, generic generators were introduced to create safe type collections, so we won’t get some unexpected object type from collections at runtime.

In addition to collections, we can also apply generalizations to methods and classes.

+1
source

There is an introduction to generics available on MSDN.

One of the simplest examples of using generics is List<T> . This means that if you want to have in your program a collection of something, such as strings, you have a choice:

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

Taking each in turn; anArrayOfStrings is an array of strings. This means that you cannot add to it or remove it. This is normal if you have a fixed number of items. anArrayListOfObject is a .net 1.0 "collection", with the disadvantage that when it takes an object , you can put something there, not just strings.

The final aListOfStrings option aListOfStrings strongly typed in that the compiler will complain about any code that tries to put something into it, is not a string. This makes your code more reliable, readable (you do not need to write code codes to make sure that you insert / delete a string) and are flexible.

+1
source

Try reading C # in depth . Here you will find great explanations of generics.

0
source

All Articles