Comparing Generics in VB.NET and C#

UPDATE: Some of the tags did not show up in the HTML (e.g. <itemType). This is corrected now... Thx Bruce.

Tonight I toyed a little bit with Generics. This feature was one of the first on my (rather long) list I wanted to try out, so I was quite curious. Thanks to the nice overview of Tom, I quickly put toghether a very simple generic collection class. The people who know me, know that I (still) prefer VB.NET over C# (I have a VB background), but I am bi-lingual, so I created the collection class both in VB.NET and C#. I noticed some minor differences between the two languages...

public class MyCollection<itemType>:System.Collections.CollectionBase
 public MyCollection():base()
 { }

 public itemType this[int index]
   return (itemType)base.List[index];
   base.List[index] = value;

 public int Add(itemType item)
  return base.List.Add(item);

Public Class MyCollection(Of itemType)
    Inherits CollectionBase

    Public Sub New()
    End Sub

    Default Public Property Item(ByVal index As Integer) As itemType
            Return CType(MyBase.List(index), itemType)
        End Get
        Set(ByVal Value As itemType)
            MyBase.List(index) = Value
        End Set
    End Property

    Public Function Add(ByVal item As itemType) As Integer
        Return MyBase.List.Add(item)
    End Function
End Class

As you can see, the structure is almost the same in VB.NET and C#, although I have to admit the C# syntax is a little bit more sexier. But the other way around: the VB.NET syntax is probably easier to understand by someone with little knowledge of Generics. Using the generic collection class is quite simple. It comes down creating a new instance of the class, and setting the type you want the collection to work with.

MyCollection c = new MyCollection<string>();

Dim c As New MyCollection(Of String)

When trying my collection both in C# and VB.NET, I noticed some differences in the Intellisense. For example when you use the Add method, the C# editor tells you, while typing, that this method expects a string value. In VB.NET Intellisense is not that smart, it can't tell you what type you need to add. Probably this is because I'm using the PDC bits, because the VB.NET editor can tell you that you can't add for example an integer to the collection (when using Option Strict ofcourse).




Comments have been disabled for this content.