Advanced Generics in VB.NET: More than one Constraint
In one of
my previous posts I tried generics both in VB.NET and C#, it turned out both
languages support generics the same way. Ofcourse there is
the syntax difference between them, and at this time C# has
Intellisense that supports generics better, but I'm pretty
sure the VB.NET team will catch up. Tonight I explored
generics a little bit more; it's possible to add constraints
to the generic type. By doing so, you are sure only
instances can be created for the generic type, that support
for example an interface you want it to. Another possibility
is a constraint so the generic types must inherit from a
specific base type. Let's say you have a base Entity class,
from which your business entity classes inherit from, and a
Customer entity class:
Public Class Entity
Private _id As Long
Public Property ID() As Long
Get
Return _id
End Get
Set(ByVal
Value As Long)
_id = Value
End Set
End Property
End Class
Public Class Customer
Inherits Entity
Private _name As String
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal
Value As String)
_name = Value
End Set
End Property
End Class
The generic collection class could look like this:
Public Class MyCollection(Of itemType As Entity)
Inherits CollectionBase
Default Public Property Item(ByVal index As Integer)
As itemType
Get
Return
CType(MyBase.InnerList(index), itemtype)
End
Get
Set(ByVal Value As itemType)
MyBase.InnerList(index) = Value
End Set
End Property
Public Function Add(ByVal item As itemType) As
Integer
Return MyBase.InnerList.Add(item)
End Function
End Class
Using the generic MyCollection class goes like this:
Dim c As New MyCollection(Of Customer)
So far pretty simple! The fun begins when you want to add
multiple constraints. I searched the internet for some
examples, but I couldn't find an example (I searched only a
minute or so, yes I'm lazy). Luckily
Yves was online and he
was following a session about generics at
U2U, so I asked
him if this was possible. His answer was positive (cool!),
but he saw this only in C#. So strengthened by the knowledge
that this was possible in C#, I searched for the syntax in
VB.NET. I tried a few possibilities, and it turned out that
you have to use the & character to add
more than one constraint. Extending the sample from above
with an additional constraint, for example the generic type
needs to implement the IComparable interface:
Public Class MyCollection(Of itemType As
Entity & IComparable)
...
End Class
By the way, the C# syntax is:
public class List<ItemType> where ItemType :
IComparable<ItemType>
Since I couldn't find any official documentation, I cannot garantuee that the syntax showed in this post is correct. So if anyone of MS reads this (by accident probably :-), it would be great if you can confirm this or give the correct syntax.