Range(Of T)
—
A range of values of the specified type
Problem
The Problem!
Solution
The Solution!
Discussion
The Discussion!
Example
This example shows how to define a range of Integers, then checks to see if a value is within that range.
Option Strict On
Dim i As New Range(Of Integer)(5, 10)
If i.Contains(2) Then
Else
End If
This example how to define a range of DateTime values, then checks to see if Today is within that range.
Option Strict On
Dim october2005 As New Range(Of DateTime)(#10/1/2005#, #10/31/2005#)
If october2005.Contains(DateTime.Today) Then
End If
This example shows that Range(Of T) can be used with any type that has Ordinality (implements IComparable).
Option Strict On
Dim i As New Range(Of Integer)(5, 10)
Dim s As New Range(Of String)("Apple", "Banana")
Dim october2005 As New Range(Of DateTime)(#10/1/2005#, #10/31/2005#)
Dim f As New Range(Of Single)(2.0F, 3.0F)
If i.Contains(2) Then
Else
End If
If october2005.Contains(DateTime.Today) Then
End If
Source
Define the generic Range(Of T) type.
Option Strict On
Option Explicit On
Public Structure Range(Of T As {IComparable(Of T), IEquatable(Of T)})
Implements IEquatable(Of Range(Of T))
Private ReadOnly m_start As T
Private ReadOnly m_end As T
Public Sub New(ByVal start As T, ByVal [end] As T)
m_start = start
m_end = [end]
End Sub
Public ReadOnly Property Start() As T
Get
Return m_start
End Get
End Property
Public ReadOnly Property [End]() As T
Get
Return m_end
End Get
End Property
Public ReadOnly Property IsEmpty() As Boolean
Get
Return m_start.CompareTo(Nothing) = 0 AndAlso m_end.CompareTo(Nothing) = 0
Return m_start.Equals(Nothing) AndAlso m_end.Equals(Nothing)
End Get
End Property
Public Function Contains(ByVal value As T) As Boolean
Return m_start.CompareTo(value) <= 0 AndAlso value.CompareTo(m_end) <= 0
End Function
Public Function Contains(ByVal value As Range(Of T)) As Boolean
Return Me.Contains(value.m_start) AndAlso Me.Contains(value.m_end)
End Function
Public Function Overlaps(ByVal value As Range(Of T)) As Boolean
Return Me.Contains(value) OrElse value.Contains(m_start) OrElse value.Contains(m_end)
End Function
Public Overrides Function GetHashCode() As Integer
Return m_start.GetHashCode() Xor m_end.GetHashCode()
End Function
Public Overloads Overrides Function Equals(ByVal obj As Object) As Boolean
If TypeOf obj Is Range(Of T) Then
Return Equals(DirectCast(obj, Range(Of T)))
Else
Return False
End If
End Function
Public Overloads Function Equals(ByVal other As Range(Of T)) As Boolean Implements IEquatable(Of Range(Of T)).Equals
Return m_start.Equals(other.m_start) AndAlso m_end.Equals(other.m_end)
End Function
End Structure
See Also