Introduction
Some New Features Have Been Added To C # language with version 2.0 of .net. Which is:
Generics Iterators Anonymous methods Partial classes In this Article I will explain about Generics Feature with some examples. Generics Generics are used to help make the code in the software components much more reusable. They are a type of data structure that contains code that remains the same . The data type of the parameters can change with each use.The usage within the data structure adapts to the different data type of the passed variables. Each time the generic is used, it can be customized for different data types without needing to rewrite any of the internal code. Generics permit classes, structs, interfaces, delegates, and methods to be parameterized by the types of data they store and manipulate. We can refer to a class, where we do not force it to be related to any specific Type, But We Can Still Perform Work with It in a Type-Safe Manner. An Example Where We Could Implement Generics Is in Dealing with Collections of Items (Integers, Strings, Orders etc.). We can create A Generic Collection Than Can Handle Any Type Manner. for Example, We Can Have A Single Array Class To Store A List of Users Or Even We Actual Use IT, WE WILL BE ABLE to access the items in the collection directly as a list of Users or items, and not as objects (with boxing / unboxing, casting). Generics Implementation Let us explore an example to understand the need for Generics and the Implementation part of it. Normally We write the arraylistclass as: class myarraylist
{
Private Object [] items;
PRIVATE INT Count = 0;
...
Public Void Add (Object Item)
{
Items [count ] = item;}
Public Object GetItem (int INDEX)
{
Return items [index];
}
}
In this code, any untyped object can be added to the list and be read. While adding an untyped object is possible in a direct manner, there has to be an explicit type conversion on a read access. The untyped declaration of the list results in two problems. The compiler has no chance to verify the content of the list and the necessary type conversions. Type failures will be recognized only at runtime-or maybe never recognized at all. You can solve both problems by using typed classes. The base class library provides an abstract base class, CollectionBase in the System.Collections namespace, that will enable you to create typed collections easily. you have to implement the body for the different methods and the indexer. Internally, the objects are stored in an untyped ArrayList, And Calls are Forwarded to this Class. For reference type, this approach works very well, although a new class Has to be explicitly developed for each data type. however, collections for value type created in this way are inefficient, because the data needs to be (un) boxed to be stored in the ArrayList internally. The solution for problems like this is the use of generic classes. A blueprint of the class is created just once. Instead of using a Particular Data Type or Object, A Specific PlaceHolder Is Added. // Defining a Generic Class
Class MyArrayList
{
Private itemtype [] items;
PRIVATE INT COUNT
...
Public Void Add (ItemType Item)
{
Items [count] = item;
}
Public ITEMTYPE GETITEM (INT INDEX)
{
Return items [index];
}
The class MyArrayList can be specialized for any data-type which would, later in the class, be referenced using the name ItemType class MyArrayListWe replaced the data type of items with ItemType. Now we can utilize MyArrayList for various types. For example, the code MyArrayList
IList = new myarraylist
();
Will create an instance of MyArrayList class that accepts and return only integers or that has replaced ItemType in class definition with int. Now we can only add and retrieve integers from iList. Static void Main ()
{
MyArrayList
IList = new myarraylist
();
IList.Add (25);
INT IVALUE2 = IList.getItem (1);
}
Similarly for User Defined Type 'Employee'
Static void main ()
{
MyArrayList
PList = New MyArrayList
();
PLIST.ADD (New Employee ("john"));
}
USING MULTIPLE TYPES
WE CAN Define More Than One Type In Generic Definition. A Practical Example Is A Dictionary That Can Be Typed Individually That The key and the value.
In this case, IT Allows Multiple Placeholders. They Have to Be Specified in Angle Brackets, Separated by Commas.
Public Class MyDictionary
{
Public Void Add (Keytype Key, ValueType Value)
{
// ...
}
Public valuepe THIS [Keytype Key]
{
Get {return valuePe.default;
}
}
Although using Generics is type safe, you do not have type-safe access while developing the class itself. Because the type with which the generic class is used later is absolutely unknown, it's internally assumed to be object. Specific members of the data type CAN Only Be Accessed After an Explicit and Therefore Unsafe Conversion. Possible Failures Will Only Be detected At Run Time.
USING METHODS
Methods Are Another Exciting Field of Use for Generics. Generic Methods Will Allow You to Pass One or More Data Types. An Example Is Given Blow.public Class Myclass
{
Protected ItemType Mymethod
(ItemType ITEM)
{
Return Item;
}
}
Conclusion
Generics are very important and useful if you work, for example, with any kind of collections. Because of the backwards compatibility of ASP.NET 2.0, the existing collections could not be modified. Instead, a new namespace named System.Collections.Generic Was Created. IT Contains a Lot of Generic Classes, Structures, and Interfaces Like the Following:
Dictionary
List
Queue
SortedDictionary
Stack
In The Case of C #, Gnerics Are Declared and Type Checked At Compile Time While Instant At Runtime Just Like Any Other Object. C # generics Has The Following Advantages:
The Program becomes statically typed, so errors are discovered at compile-time. No runtime casts are required and the program runs faster. Primitive type values (e.g int) need not be wrapped. Hence the program is faster and uses less space.
Reference: ASP.NET 2.0 REVEALED, by Patrick Lorenz.