Visual Basic: SafeLeft/SafeRight Help Extensions

Posted by Blake on 7/29/2011
)

I do still use the VB Left/Right functions instead of SubString. Call me a creature of habit. I’ve created a helper extension method that won’t throw an exception if the length requested is greater than the length of the string. Instead, it will return the entire contents of that string. Remember, to use this, the file with these methods will need to import “System.Runtime.CompilerService” and the code that needs to use it will need to Import the Namespace you put these methods in (or, you can call them like a regular method an not as an extension). Personally, I love extension methods as a way to find the methods I need quickly via Intellisense. These are also PCL compliant.

        ''' <summary>
        ''' Returns the specified number of characters from the left hand side of the string.  If the number asked for is longer the
        ''' string then the entire string is returned without an exception.
        ''' </summary>
        ''' <param name="str"></param>
        ''' <param name="length"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        <Extension()> _
        Public Function SafeLeft(ByVal str As String, ByVal length As Integer) As String
            If length >= str.Length Then
                Return str
            ElseIf length < 0 Then
                Return ""
            End If
            Return Left(str, length)
        End Function

        ''' <summary>
        ''' Returns the specified number of characters from the right hand side of the string.  If the number asked for is longer the
        ''' string then the entire string is returned without an exception.
        ''' </summary>
        ''' <param name="str"></param>
        ''' <param name="length"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        <Extension()> _
        Public Function SafeRight(ByVal str As String, ByVal length As Integer) As String
            If length >= str.Length Then
                Return str
            ElseIf length < 0 Then
                Return ""
            End If
            Return Right(str, length)
        End Function