How to Limit an Input Value to a Specific Range Using a Generic Extension Method





4.00/5 (1 vote)
A generic extension method that allows my program to limit an input to a specific range
I created a generic extension method that allows my program to limit an input to a specific range. This code is targeted for .NET 4 Client, but should also work in .NET 3.5.
Module ObjectExtensions
<System.Runtime.CompilerServices.Extension()>
Public Function LimitToBetween(Of T As IComparable)_
(ByRef ThisObject As T, ByVal LowerValue As T, ByVal UpperValue As T) As T
Dim bSkip As Boolean
Dim oReturn As T
Select Case ThisObject.CompareTo(LowerValue)
Case Is < 0
oReturn = LowerValue
bSkip = True
Case Is = 0
Case Is > 0
End Select
If Not bSkip Then
Select Case ThisObject.CompareTo(UpperValue)
Case Is < 0
Case Is = 0
Case Is > 0
oReturn = UpperValue
bSkip = True
End Select
End If
If Not bSkip Then
oReturn = ThisObject
End If
Return oReturn
End Function
End Module
An example usage:
Dim lValue As Int16 = 5237
Console.WriteLine(lValue.LimitToBetween(5000, 6000))
' Returns 5237
Console.WriteLine(lValue.LimitToBetween(4000, 5000))
' Returns 5000
Console.WriteLine(lValue.LimitToBetween(6000, 7000))
' Returns 6000
Dim sValue As String = "lmn"
Console.WriteLine(sValue.LimitToBetween("a", "j"))
' Returns "j"
Console.WriteLine(sValue.LimitToBetween("k", "t"))
' Returns "lmn"
Console.WriteLine(sValue.LimitToBetween("u", "z"))
' Returns "u"