Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / .NET / .NET4

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

4.00/5 (1 vote)
19 Feb 2013CPOL 5.3K  
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.

VB.NET
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:

VB
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"

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)