Click here to Skip to main content
12,623,903 members (28,712 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

3.4K views
1 bookmarked
Posted

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

, 19 Feb 2013 CPOL
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
  <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"

License

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

Share

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...

Pro
Pro

Comments and Discussions

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