programming, .NET, linux and others

F# - Defining an extension method for generic arrays

by Gregor Uhlenheuer on August 16, 2012

Lately I wanted to write a small extension method for the Array class in F#. What would be a pretty simple task in C# appears to be a bit more tricky in F#.

public static T GetOrDefault<T>(this T[] elements, int n)
    if (elements.Length > n)
        return elements[n];
    return default(T);

After trying a few things without any success I found a solution on StackOverflow that I want to share with you.

Basically this is what it has to look like in F#:

type 'a ``[]`` with
    member x.GetOrDefault(n) =
        if x.Length > n then x.[n]
        else Unchecked.defaultof<'a>

The trick is to use the backticks notation to define the array class. As stated in the mentioned post you can extend via the IList<_> generic interface as well:

type System.Collections.Generic.IList<'T> with
    member x.GetOrDefault(n) =
        if x.Count > n then x.[n]
        else Unchecked.defaultof<'a>

This post is tagged with f#, .net and programming