Sunday, September 16, 2007

Most Power full feature of .NET 2.0 languages: Generics

The type system of a programming language enables us to check for illegal instructions and memory violations at compile time. Defining the types for values at design time allows us to detect related bugs in the code at compile time in all the strongly typed languages, including C# and VB.net (using Option Explicit On). Since the binding is done early, it makes the code run faster and thus increases its performance. In spite of all these advantages, type system has some disadvantages. It reduces flexibility of the code and restricts its reusability. If the same type of operations is to be executed on two different types of values, we need to rewrite the code for each type. For example, if we need to write stack classes for String and Integer values, we will have to write two classes for it.
As a solution to the above problem, Microsoft has added a cool feature known as Generics to .NET 2.0. Actually, Generics is the parametric polymorphism that is supported by many programming languages but has not been available in .NET languages till now. In .NET, Generics is the type extension of the Common Language Runtime (CLR). Using generics, we can write code that is type-safe, runs faster and works with any data type. As the CLR supports many languages, you can write the generic code in any .NET language. Depending on the language, syntax of the generic code will also change, however, they are absolutely inter-usable with each other.
In generics, we specify the data type as the replaceable element. This missing information is completed in the consumer code using the (of T) construct. The capital “T” is used by convention and can be replaced by any letter.
When we define the class with (Of Integer), it uses the Integer type wherever we have specified the “T” type and, similarly, when we define the class with (Of String), it uses the String type wherever we have specified the “T” type in the class. As the data types of generic classes are determined at compile time, it reduces the chances of illegal assignments. There is no need of casting, which increases the performance of the code. As the class works with all data types, there is a substantial increase in the code reuse.

Not only can Generics be used at the class level, we can also write generic code at the procedure level. Following is the code in VB.NET 2.0 to explain generics.

Public Sub Swap(Of T)(ByRef Val1 As T, ByRef Val2 As T)
Dim tmp As T
tmp = Val1
Val1 = Val2
Val2 = tmp
End Sub

In case we would like to use the above procedure for integer values, we will call the procedure in the consumer code as:
Dim j, k As Integer
j = 10
k = 100
Swap(Of Integer)(j, k)

Similarly, in case of String values, we will write the calling code as:
Dim str1, str2 As String
str1 = "sushant"
str2 = "verma"
Swap(Of String)(str1, str2)

No comments: