what advantage from using Generic <T>

phicha

Well-known member
Joined
May 11, 2009
Messages
45
Programming Experience
Beginner
i just learn about generic, can someone explain me why should we using generic code ? and what the advantage from using it.

since i read it that it will lock a class so only can inputed by one type data only


thanks,
 
The most commonly used generic type is the List(Of T), which acts as a dynamic array. With an array, you can specify the type of the elements it contains. If you want Strings ten you specify a String array; if you want Integers then you specify and Integer array and etc. This means that the compiler can prevent you from mistakenly adding data of the wrong type in code. It also means that storage of value types like Integer is as efficient as can be. Finally, it means that when you retrieve an element you get ti back as its specific type.
VB.NET:
Dim strings As String() = {"Peter", "Paul", "Mary"}
Dim integers As Integer() = {1, 2, 3}

Dim myString As String = strings(0)
Dim myInteger As Integer = integers(2)
In .NET 1.x, if you wanted a dynamic array behaviour you had to use an ArrayList. Unlike an array, an ArrayList could grow and shrink dynamically as you added and removed items. This made it much more flexible. The problem was that the items in an ArrayList are all Object references. This means that, even if your intention is only to store Strings or only store Integers, there's no way top enforce that. It also means that value types like Integer get boxed, which means that storing and retrieving them is less efficient and slower. Finally, it means that, with Option Strict On (as it should always be), you have to cast items as you retrieve them from type Object to their actual type:
VB.NET:
Dim strings As New ArrayList
Dim integers As New ArrayList

strings.Add("Peter")
strings.Add("Paul")
strings.Add("Mary")

integers.Add(0)
integers.Add(1)
integers.Add(2)

Dim myString As String = CStr(strings(0))
Dim myInteger As Integer = CInt(integers(2))
From .NET 2.0 you have the List(Of T) class, which works much like the ArrayList class except that you get to specify what type T is when you create the List. Whatever type you specify, only objects of that type can be added to the List and each item you get back will be that type, so no casting is required. Value types are also stored without being boxed, so that makes the List more efficient. As such you get all the type safety of an array but the convenience of dynamic resizing like the ArrayList:
VB.NET:
Dim strings As New List(Of String)
Dim integers As New List(Of Integer)

strings.Add("Peter")
strings.Add("Paul")
strings.Add("Mary")

integers.Add(0)
integers.Add(1)
integers.Add(2)

Dim myString As String = strings(0)
Dim myInteger As Integer = integers(2)
There's a lot more to generics than just the List(Of T) class and a lot more than just collections, but hopefully just the List(Of T) class, which is what you'll probably use most often, demonstrates their goodness.
 
and how about if
there is method that using <T> before the parameter ?
and how when we using where function ?

thanks a lot for long explaination.
i appreciate it very much

thanks again
 
First up, <T> is C# syntax. (Of T) is used in VB.

Just as for a List(Of T), where you specify what T is when you create an instance of the class, so to you specify what T is when you call a generic method. For instance, consider the Array.Sort(Of T)(T(), Comparison(Of T)) method. That looks fairly complicated, right? All it's saying is that there is an Array.Sort method with a generic type parameter T where the method has two parameters: one that's an array of T objects and one that is a Comparison(Of T) delegate. That says that you can call that method with an array of any type you like, as long as you pass a Comparison delegate of the same generic type. A Comparison(Of T) delegate is reference to a method that takes two T objects and returns an Integer indicating their relative order. Here are some examples of how you might call this method:
VB.NET:
Module Module1

    Sub Main()
        Dim strings As String() = {"peach", "zebra", "anvil", "truck"}

        Array.Sort(Of String)(strings, New Comparison(Of String)(AddressOf CompareStringsDescending))

        For Each Str As String In strings
            Console.WriteLine(Str)
        Next

        Console.ReadLine()
    End Sub

    Private Function CompareStringsDescending(ByVal x As String, ByVal y As String) As Integer
        Return y.CompareTo(x)
    End Function

End Module
That code is completely explicit, because it specifies at every point what T is. In this case, T is String. The method generic type parameter is specified as String and so is the generic type parameter of the Comparison delegate. If T is set to String and the Sort method requires an array of T then in this case it requires an array of String, which the code is passing.

You don;t need to be so explicit though. With generics, you only need to set the generic type parameter in one place and that sets it everywhere. As such, that code could be simplified to this:
VB.NET:
Module Module1

    Sub Main()
        Dim strings As String() = {"peach", "zebra", "anvil", "truck"}

        Array.Sort(strings, AddressOf CompareStringsDescending)

        For Each Str As String In strings
            Console.WriteLine(Str)
        Next

        Console.ReadLine()
    End Sub

    Private Function CompareStringsDescending(ByVal x As String, ByVal y As String) As Integer
        Return y.CompareTo(x)
    End Function

End Module
That code does exactly the same thing as the previous snippet but the generic type is set implicitly. In this case we are passing an array of String and therefore the system knows that T must be String. As such it knows that the second parameter must be a Comparison(Of String). The signature of the specified method matches so one is created automatically.
 
VB.NET:
Module Module1

    Sub Main()
        Dim strings As ip() = {New ip(2), New ip(1), New ip(4), New ip(3), New ip(5)}
        Array.Sort(Of ip)((strings), New Comparison(Of ip)(AddressOf CompareStringsDescending))
        'this previous sort, does it mean 
        'Array.Sort(only sort ip class)(( sort strings object), the rest properties what does it mean ?)
        'Array.Sort(strings)
        For Each ip As ip In strings
            Console.WriteLine(ip.angka)
        Next

        Console.ReadLine()
    End Sub

    Class ip
        Implements IComparable
        Public angka As Integer
        Sub New(ByVal int As Integer)
            angka = int
        End Sub

        Public Function CompareTo(ByVal obj As Object) As Integer Implements IComparable.CompareTo
            If Me.angka > CType(obj, ip).angka Then
                Return 1
            ElseIf Me.angka = CType(obj, ip).angka Then
                Return 0
            Else
                Return -1
            End If
        End Function
    End Class

    Private Function CompareStringsDescending(Of ip)(ByVal x As ip, ByVal y As ip) As Integer '<-- what function (of ip) on here ?
        Return y.CompareTo(x) ' why not working ? i just learned implement comparable
        'Return y.

    End Function

End Module

it sure a lot confusing me.

thanks a lot..
 
Last edited:
CompareStringsDescending(Of ip) here you are not specifying a specific type, you are specifiying a variable for a generic type, a type holder. In effect you are hiding the 'ip' type by declaring the generic 'ip' name. Compare with this:
VB.NET:
Private Function CompareDescending(Of T As IComparable)(ByVal x As T, ByVal y As T) As Integer
    Return y.CompareTo(x)
End Function
The point of generics is that the classes/methods should work with any type specified, so when writing generics forget the specific type.

The alternative is to write a type specific method, not using generics, like this:
VB.NET:
Private Function CompareDescending(ByVal x As ip, ByVal y As ip) As Integer
    Return y.CompareTo(x)
End Function

Usage sample, here the specific type is specified:
VB.NET:
Dim ips As ip() = {New ip(2), New ip(1), New ip(4), New ip(3), New ip(5)}

Array.Sort(Of ip)(ips, New Comparison(Of ip)(AddressOf CompareDescending))
' or 
Array.Sort(ips, AddressOf CompareDescending)
Notice that the usage samples would work with both the comparison functions above with no change in code.
 
Back
Top