Want a quick and easy way to add capabilities to bulit-in classes and types without subclassing? Try extension methods.
An extension method is a method that is called using syntax that indicates it belongs to another object. For example, say you really don’t like writing code like this that increments an integer value:
downloadCounter = downloadCounter + 1
With an extension method for Integer, you could instead write something like this:
downloadCounter.Add
Essentially, extension methods are global methods that use the Extends keyword to allow you to write the method using dot notation. This describes the first rule, which is that extension methods must be global methods on modules. The extension method for this Add method looks like this:
Sub Add(ByRef Extends i As Integer, amount As Integer = 1) i = i + amount End Sub
Since this takes an optional parameter, you could also write:
downloadCounter.Add(5)
to mean:
downloadCounter = downloadCounter + 5
There is a lot more you can do with extension methods, but they are particularly useful for adding methods like this to the built-in data types (such as Integer) that are not available for subclassing.
Another good example is adding a DoubleQuote method that can be used to quote strings:
Function DoubleQuote(Extends s As String) As String Return """" + s + """" End Function
Of course, you can also extend regular classes as well. This example extends DesktopListBox to add a search function that will search and select a row that contains a specific column value:
Sub Find(Extends lb As DesktopListBox, findText As String, column As Integer = 0)
For i As Integer = 0 To lb.LastRowIndex
If lb.CellTextAt(i, column) = findText Then
lb.SelectedRowIndex = i
Exit For
End If
Next
End Sub
You use it by supplying the text to find and, optionally, the column to search in. This just searches the first column:
ListBox1.Find("MyValue")
Extensions are a great way to make your code more readable and to easily add useful “utility” methods. To learn more about extension methods, refer to the Docs.
There’s an extension method example that is included with Xojo which you can find in the Examples section of the Project Chooser: Examples/Language/Extension Methods
Paul learned to program in BASIC at age 13 and has programmed in more languages than he remembers, with Xojo being an obvious favorite. When not working on Xojo, you can find him talking about retrocomputing at Goto 10 and on Mastodon @lefebvre@hachyderm.io.
