Benefits of Generics
1. Generics are checked at compile-time. When your program instantiates a generic class with a supplied type parameter, the type parameter can only be of the type your program specified in the class definition. For example, when your program created a Stack of Customer objects, it was no longer able to push an integer onto the stack. By enforcing such behavior, you can build code that is more consistent.
2. Generics permit programmers to author, test, and deploy code once, and then reuse that code for a variety of different data types.This is true of the first Stack example. The second Stack example allows your program to reuse code with a negligible performance impact to its applications. For value types, the first Stack example imposes a significant performance penalty, whereas the second Stack example eliminates the penalty entirely because you have eliminated boxing and downcasts.
3. Your program can encapsulate all behavior associated with a stack in one convenient class by creating one Stack class,. Then, when you create a Stack of Customer types, it is still obvious that your program is using a stack data structure, albeit with Customer types stored within it.
4. The C# implementation of generics reduces code bloat when compared to other strongly-typed implementations. By creating typed collections with generics, you can avoid the need to create specific versions of each class while retaining the performance benefits of doing so. For example, your program can create one parameterized Stack class and avoid having to create an IntegerStack to store integers, a StringStack to store strings, or a CustomerStack to store Customer varieties.
Various Types of Parameters
Generic types can use any number of parameter types. In the previous Stack example, only one type was used. Suppose you created a simple Dictionary class that stored values alongside keys. Your program could define a generic version of a Dictionary class by declaring two parameters, separated by commas within the angle brackets of the class definition:
public class Dictionary<KeyType, ValType> { public void Add(KeyType key, ValType val) { ... } public ValType this[KeyType key] { ... } }
You have to supply multiple parameters within the angle brackets of the instantiation statement when using the Dictionary class. Again separated by commas, and supply the right types to the parameters of the Add function and indexer:
Dictionary<int, Customer> dict = new Dictionary<int, Customer>(); dict.Add(3, new Customer()); Customer c = dict.Get[3];
Wish you the best!