VB.NET v2.0: Generics are Supported in VB Also

Rob Chartier has created a really nice article titled Introducing .NET Generics.  Unfortunately, all of the sample code was written using C# -- just like every sneak peek on generics so far.  However, VB.NET will also fully support generics in .NET v2.0 (Whidbey), although not much has been stated about this.  Take a look at my VB.NET translations here -- you'll note that Of is the VB keyword used for generics, instead of using the <> syntax of C#. 

Given Rob's C# first generic type:

public class Col<T> {
  T t;
  public T Val {
    
get {
      return t;
    }
    
set {
      t =
value;
    }
  }

}

Here's the equivalent VB generic type:

Public Class Col(Of T)
  Dim _t As T
  Public Property Val() As T
    Get
      Return _t
    End Get
    Set(ByVal value As T)
      _t = value
    End Set
  End Property
End Class

Given Rob's C# first generic usage:

Col<string> mystring = new Col<string>();

Here's the equivalent VB generic usage:

Dim mystring As New Col(Of String)

Rob has a C# generic method also:

public static T[] CreateArray<T>(int size) {
  return new T[size];
}

And here's the equivalent VB again:

Public Shared Function CreateArray(Of T)(ByVal size As Integer) As T()
  Dim _t(size) As T
  Return _t
End Function

It looks like VB.NET also allows constraints on generics, although I haven't tested this yet.  I personally prefer C#, but I find many potential customers are interested in VB.NET, including my current employer.  So far C# is getting the headlines in v2.0, but it looks like VB.NET is doing just fine too.  By the way, the System.Collections.Generics namespace is full of pre-built generic collections, like Dictionary, List, Queue, Stack, and many others too.

No Comments