Example. This program introduces an extension method called LastChar. This method is called upon a String instance. It is called like a String method, but it is not defined on the String type.
Here LastChar() returns the final char in a string. It first checks that the string is not Nothing, and has one or more chars.
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.
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 ModuleC
?
?
Discussion. When should you use extension methods in VB.NET programs? If a small and useful method is used often, it may be helpful to turn it into an extension method.
And I often use extension methods to test characters and strings. For example, I use a "IsUpperOrDigit" extension method.
Info No such method exists in the .NET Framework, but the implementation is obvious.
Warning I usually end up with too many extension methods. It is preferable to limit the number, and have strict requirements.
An extension method changes the syntax for calling a method. It makes a non-Class method look like a Class method. This sometimes can yield simpler programs that are easier to read.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jun 29, 2023 (edit).