Type extensions
Definition
Members of a type defined outside its main type
block.
Each of these members is called augmentation or extension.
3 categories of extension :
Intrinsic extension
Optional extension
Extension methods
Intrinsic extension
Declared in the same file and namespace as the type
Use case: Features available in both companion module and type
β E.g. List.length list
function and list.Length
member
How to implement it following top-down declarations?
1. Implement in type, Redirect module functions to type members β More straightforward
2. Intrinsic extensions: β Declare type "naked", Implement in module, Augment type after β Favor FP style, Transparent for Interop
Example:
Optional extension
Extension defined outside the type module/namespace/assembly
Use cases:
Types we can't modify, for instance coming from a library
Keep types naked - e.g. Elmish MVU pattern
Compilation: into static methods β Simplified version of the previous example:
Another example:
Limits
Must be declared in a module
Not compiled into the type, not visible to Reflection
Usage as pseudo-instance members only in Fβ― β in Cβ―: as static methods
Type extension vs virtual methods
β Override virtual methods:
in the initial type declaration β
not in a
type extensionβ
Type extension vs type alias
Incompatibleβ
π‘ Solution: use the real type name
β Corollary: Fβ― tuples such as int * int
cannot be augmented, but they can be extended using Cβ―-style extension methods π
Type extension vs Generic type constraints
Extension allowed on generic type except when constraints differ:
Solution: Cβ―-style extension method π
Extension method (Cβ―-style)
Static method:
Decorated with
[<Extension>]
In Fβ― < 8.0: Defined in class decorated with
[<Extension>]
Type of 1st argument = extended type (
IEnumerable<'T>
below)
Example:
Cβ― equivalent:
Tuples
An extension method can be added to any Fβ― tuple:
Comparison
Methods
β instance, β static
β instance, β static
Properties
β instance, β static
β Not supported
Constructors
β intrinsic, β optional
β Not supported
Extend constraints
β Not supported
β Support SRTP
Limits
Type extensions do not support (sub-typing) polymorphism:
Not in the virtual table
No
virtual
,abstract
memberNo
override
member (but overloads π)
Extensions vs Cβ― partial class
Cβ― partial class
β Yes
β Yes
Only partial class
Extension intrinsic
β No
β Yes
β Yes
Extension optional
β Yes
β No
β Yes
Last updated
Was this helpful?