Extension Types
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 class
keyword is prefixed with the __extension
keyword. 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 __extension class String_Helpers : String
{
int NumberOfOcurrencesOfCharacter(Char character)
{
...
}
}
Inside the implementation, the extended type instance can be referred to via the this
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 declare both instance and static members. They can add methods and properties with getter/setter statements, but they cannot add new data storage (such as fields, or properties with an implied field), because the underlying structure of the type being extended is fixed and cannot be changed.
Extensible Types
Extensions can be defined for any named type, be it a Class, Struct, Interface, Enum, or Block.
No matter which kind of type is being extended, the extension will always use the class
keyword.