Click here to Skip to main content
13,248,562 members (88,280 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


1 bookmarked
Posted 19 Feb 2013

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

, 19 Feb 2013
Rate this:
Please Sign up or sign in to 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
  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"


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


About the Author

Adam Zuckerman
Software Developer (Senior)
United States United States
Long time software engineer who rambles occasionally about coding, best practices, and other random things.

You may also be interested in...


Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171114.1 | Last Updated 19 Feb 2013
Article Copyright 2013 by Adam Zuckerman
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid