VB.NET Extension MethodUse the Extension attribute from System.Runtime.CompilerServices to create an extension method.
method syntax is available in VB.NET. With it, we call a method in a separate Module as though it is defined on the Class. This sometimes leads to clearer syntax. We use the Extension attribute.Class
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.
LastChar: This returns the final char in a string. It first checks that the string is not Nothing, and has one or more chars.Nothing
Tip: 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
' Test extension on a string.
Dim v As String = "ABC"
' Test nothing value.
v = Nothing
' Test empty string.
v = ""
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)
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. This eliminates the need to remember a Class name.
In my programs,
I often use extension methods to test characters and strings. For example, I use a "IsUpperOrDigit" extension method. No such method exists in the .NET Framework, but the implementation is obvious.
Caution: 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 leads to confusion and excess complexity. But it often can yield simpler programs that are easier to read.LINQ
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.