Type extensions can be used to expand an existing type with new methods or properties.
Extensions are most commonly used to add custom helper methods, often specific to a given project or problem set, to a more general type provided by the framework, or to correct perceived omissions from a basic type's API.
For example, a project might choose to extend the
String type with convenience methods for common string operations that the project needs, but that are not provided by the actual implementation in the platform.
Extension declarations look like regular Class declarations, except that the
Extends keyword is used (required) in lieu of
Inherits, to indicate the type that is being extended. Extensions need to be given a unique name and state the type they extend in place of the ancestor. It is common (but not mandatory) to use the original type's name, appended with the unique suffix.
Public Class String_Helpers Extends String Public Sub NumberOfOcurrencesOfCharacter(character as Char) As Integer ... Sub End End Class
Inside the implementation, the extended type instance can be referred to via the
Me keyword, and all its members can be accessed without prefix, as if the extension method was part of the original type. Note that extensions do not have access to
Private or otherwise invisible members. Essentially they underlie the same access controls as any code that is not part of the original type itself.
Extension types can add any kind of member that does not imply storage, including:
- Properties with Getter/Setter
Subs/Functions and Properties added by an extension class can be instance (the default) or static (
Shared). Extension types cannot add members that require/definde storage on the class itself, sjuch as fields, events or properties with an implied field.
Extensions can be defined for any named type, be it a Class, Struct, Interface, Enum, or Block. The type does not have to originate from the same project as the extension.
No matter which kind of type is being extended, the extension will always use the