Wednesday, May 28, 2008

Creating Generic Range Class

Level: Beginner

Knowledge Required:
Generics in Visual Basic

Description:
In this article we will create a Generic Range Class, which can be further used in different types of Applications like Database Applications.

Generic Range Class:
Public Class GenericRange(Of T)
Private _Start As T
Private _End As T
Private _HasStart As Boolean
Private _HasEnd As Boolean

Public Sub New()
Call Me.SetStartNull()
Call Me.SetEndNull()
End Sub

Public Sub New(ByVal Start As T, ByVal [End] As T)
Me.Start = Start
Me.End = [End]
End Sub

Public Property Start() As T
Get
If Me.HasStart Then
Return Me._Start
Else
Throw New Exception("Start Value is NOT Set")
End If
End Get
Set
(ByVal value As T)
If value Is Nothing Then
Me.SetStartNull()
Else
Me._Start = value
Me._HasStart = True
End If
End Set
End Property

Public Property
[End]() As T
Get
If Me.HasEnd Then
Return Me._End
Else
Throw New
Exception("End Value is NOT Set")
End If
End Get
Set
(ByVal value As T)
If value Is Nothing Then
Me
.SetEndNull()
Else
Me._End = value
Me._HasEnd = True
End If
End Set
End Property

Public ReadOnly Property
HasStart() As Boolean
Get
Return Me
._HasStart
End Get
End Property

Public ReadOnly Property
HasEnd() As Boolean
Get
Return Me
._HasEnd
End Get
End Property

Public Sub
SetStartNull()
Me._HasStart = False
End Sub

Public Sub
SetEndNull()
Me._HasEnd = False
End Sub
End Class

Usage:
Private Function GetOrderQueryByDate(ByRef GR As GenericRange(Of Date)) As String
Dim sQuery As String
Dim
sWhere As String = ""

sQuery = "SELECT * FROM Orders"

If GR.HasStart Then
sWhere = "OrderDate >= '" & GR.Start & "'"
End If
If
GR.HasEnd Then
If sWhere <> "" Then sWhere &= " AND "
sWhere &= "OrderDate <= '" & GR.End & "'"
End If
If
sWhere <> "" Then
sQuery &= " WHERE " & sWhere
End If
Return
sQuery
End Function

No comments: