C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
LastChar: This returns the final char in a string. It first checks that the string is not Nothing, and has one or more chars.
NothingTip: In the Extensions module, we use the <Extension()> syntax. The parameter String is the instance the extension method is called upon.
Info: You can have more parameters on an extension method. The first one is always the instance the method is called upon.
Important: The System.Runtime.CompilerServices namespace must be imported. This provides access to the Extension attribute.
VB.NET program that uses Extension method
Imports System.Runtime.CompilerServices
Module Module1
Sub Main()
' Test extension on a string.
Dim v As String = "ABC"
Console.WriteLine(v.LastChar())
' Test nothing value.
v = Nothing
Console.WriteLine(v.LastChar())
' Test empty string.
v = ""
Console.WriteLine(v.LastChar())
End Sub
End Module
Module Extensions
<Extension()>
Public Function LastChar(ByVal value As String) As Char
' If string is not nothing, and has at least one char,
' ... return last char.
' Otherwise return a question mark.
If Not value = Nothing Then
If value.Length >= 1 Then
Return value(value.Length - 1)
End If
End If
Return "?"c
End Function
End Module
Output
C
?
?
Caution: I usually end up with too many extension methods. It is preferable to limit the number, and have strict requirements.