Sometimes you run into a situation where you want to add functionality to an existing data type. It might be a string, integer, array or perhaps one of the built in classes that you want to add new functionality to.
Exactly how do you do this ?
You can’t just edit the framework and add new methods to the String type.
And that is probably a good thing. Imagine if every user could edit String and add methods to it. There might be a huge plethora of incompatible implementations of String very rapidly.
Since you cannot edit String what can you do ?
Extension methods!
You CAN create a method type that is almost indistinguishable from a method in the base type itself. First I would suggest creating a Module named with a meaningful name. For a Module to add new method to the String data type I would name the module StringExtensions so its very clear what this module contains.
The in this module you can add GLOBAL methods. And each method in the module should have a signature that uses the extends keyword.
I’ll demonstrate. Suppose we wanted to add a new method to String that checks if the first letter of the string is a digit. We’ll name that method IsDigit.
For create a new desktop project.
Add a Module to the project called StringExtensions.
Then add a method to the StringExtensions module and name the method IsDigit.
The parameters for this method should be
extends aString as String
Note the use of EXTENDS. This is the hint to the compiler that this method should be treated as if it were one of the methods in the framework for the String datatype.
The return type for this method should be Boolean.
The code in the method should be
If aString.Trim = "" Then
Return False
End If
If InStr( "0123456789", aString.Left(1) ) > 0 Then
Return True
End If
return false
The finished method should appear like
Then in the Open, or in 2019r2 the Opening event, you can test the new extension method with code like
Dim s As String
s = "abc"
If s.IsDigit Then
Break
End If
s = ""
If s.IsDigit Then
Break
End If
s = "1abc"
If s.IsDigit Then
Break
End If
The first two cases should return false. And the last one should return true.
The only thing to be careful about with extension methods is :
- you cant name the Module the same as the datatype. The IDE will generally prevent you from doing this.
- you have to not create a new extension that may conflict with one that is in the framework.
- you have to be careful not to create one that will cause the compiler to decide there is an ambiguous use case where it cant decide which one to call. This can happen when you use optional parameters.
But other than that you can extend most datatypes, even ones in the framework, relatively easily.