What is the equivalent in F# of the C# default keyword?

Viewed 11874

I'm looking for the equivalent of C# default keyword, e.g:

public T GetNext()
{
    T temp = default(T);
            ...

Thanks

2 Answers

Technically speaking the F# function Unchecked.defaultof<'a> is an equivalent to the default operator in C#. However, I think it is worth noting that defaultof is considered as an unsafe thing in F# and should be used only when it is really necessary (just like using null, which is also discouraged in F#).

In most situations, you can avoid the need for defaultof by using the option<'a> type. It allows you to represent the fact that a value is not available yet.

However, here is a brief example to demonstrate the idea. The following C# code:

    T temp = default(T);
    // Code that may call: temp = foo()
    if (temp == default(T)) temp = bar(arg)
    return temp;

Would be probably written like this in F# (using imperative features):

    let temp = ref None
    // Code that may call: temp := Some(foo())
    match !temp with 
    | None -> bar(arg)
    | Some(temp) -> temp

Of course this depends on your specific scenario and in some cases defaultof is the only thing you can do. However, I just wanted to point out that defaultof is used less frequently in F#.

Related