How do I create an extension method in F#, for example, like this C# extension:
public static string Right(this string host, int index) { return host.Substring(host.Length - index); }
To define and call the extension methodDefine a static class to contain the extension method. The class must be visible to client code. For more information about accessibility rules, see Access Modifiers. Implement the extension method as a static method with at least the same visibility as the containing class.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
In C#, the extension method concept allows you to add new methods in the existing class or in the structure without modifying the source code of the original type and you do not require any kind of special permission from the original type and there is no need to re-compile the original type.
An extension method allows you to add functionality to an existing type without modifying the original type or creating a derived type (and without needing to recompile the code containing the type that is extended.)
For an F# extension that can be called from F#:
type System.String with member x.Right(index) = x.Substring(x.Length - index)
Note that as of Beta 1, this doesn't result in a C#-compatible extension method.
For generating extension methods visible from C# (but not usable as extension methods in F#), see the link in Brian's edit to the original post.
I know this doesn't really answer your question, but it is worth pointing out. In F# and other functional languages you often see modules with static methods (Like the Seq module) that are designed to be composed with other functions. As far as I've seen, instance methods aren't easily composed, which is one reason why these modules exist. In the case of this extension, you may want to add a function to the String module.
module String = let right n (x:string) = if x.Length <= 2 then x else x.Substring(x.Length - n)
It then would be used like so.
"test" |> String.right 2 // Resulting in "st" ["test"; "test2"; "etc"] |> List.map (String.right 2) // Resulting in ["st"; "t2"; "tc"]
Though in this case the extension method wouldn't be much more code.
["test"; "test2"; "etc"] |> List.map (fun x -> x.Right 2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With