Generics in VB.NET


Saw these cups knocking about recently.


I like the implementation of Generics in VB.NET. When you describe a generic type in C# or Java, and you have a type Database<T> you say a "database of T". VB.NET takes this further, the syntax is just Database(of T).

Generics allow you to resuse a class or a method for multiple types that need the same abstract functionality. A good example is two entities in your system that need to be persisted. The entities have different logic and a different reason to exist but they both need to be saved to a database. In this case you can implement the same functionality twice or reuse one class but allow it to be flexible enough to handle both entities.

I saw the picture of that cup knocking about on Twitter recently then I saw people wearing TShirts at a recent Scott Gu talk on Microsoft Azure. I would like to get my hands on an official one!


Public MustInherit Class ReadModel
Public Property Id As Guid
End Class
Public Class Appointment
Inherits ReadModel
Public Property StartTime As DateTime
Public Property EndTime As DateTime
End Class
Public Class Person
Inherits ReadModel
Public Property FirstName As String
Public Property LastName As String
End Class
Public Class Repository
Private _database As IDictionary(Of Type, IDictionary(Of Guid, ReadModel))
Public Sub New()
_database = New Dictionary(Of Type, IDictionary(Of Guid, ReadModel))
End Sub
Public Sub Save(Of TReadModel As ReadModel)(readmodel As TReadModel)
If Not _database.ContainsKey(GetType(TReadModel)) Then
_database.Add(GetType(TReadModel), New Dictionary(Of Guid, ReadModel))
End If
_database(GetType(TReadModel)).Add(readmodel.Id, readmodel)
End Sub
Public Function Load(Of TReadModel As ReadModel)(id As Guid) As TReadModel
Return CType(_database(GetType(TReadModel))(id), TReadModel)
End Function
End Class
<TestClass()>
Public Class RepositoryTests
<TestMethod()>
Public Sub PersonRepositoryTest()
Dim repo As New Repository
Dim person1 = New Person() With {.Id = Guid.NewGuid, .FirstName = "Dom", .LastName = "Finn"}
Dim person2 = New Person() With {.Id = Guid.NewGuid, .FirstName = "Billy", .LastName = "Finn"}
repo.Save(Of Person)(person1)
repo.Save(Of Person)(person2)
Dim person1Loaded = repo.Load(Of Person)(person1.Id)
Assert.IsNotNull(person1)
End Sub
<TestMethod()>
Public Sub AppointmentRepositoryTest()
Dim repo As New Repository
Dim app1 = New Appointment() With {.Id = Guid.NewGuid, .StartTime = New DateTime(2015, 1, 1, 9, 0, 0), .EndTime = New DateTime(2015, 1, 1, 9, 30, 0)}
Dim app2 = New Appointment() With {.Id = Guid.NewGuid, .StartTime = New DateTime(2015, 1, 2, 9, 0, 0), .EndTime = New DateTime(2015, 1, 2, 9, 30, 0)}
repo.Save(Of Appointment)(app1)
repo.Save(Of Appointment)(app2)
Dim person1Loaded = repo.Load(Of Appointment)(app1.Id)
Assert.IsNotNull(app1)
End Sub
End Class
SHARE

Dom Finn

  • Image
  • Image
  • Image
  • Image
  • Image
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment