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

11,615

Solution 1

I found this in a blog: "What does this C# code look like in F#? (part one: expressions and statements)"

C# has an operator called "default" that returns the zero-initialization value of a given type:

default(int) 

It has limited utility; most commonly you may use default(T) in a generic. F# has a similar construct as a library function:

Unchecked.defaultof<int>

Solution 2

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#.

Share:
11,615

Related videos on Youtube

elmattic
Author by

elmattic

Updated on June 22, 2020

Comments

  • elmattic
    elmattic almost 4 years

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

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

    Thanks

  • doppelgreener
    doppelgreener over 10 years
    In your C# example, you use an assignment operator instead of an equality operator inside the if statement. Is that deliberate?
  • Martin Bodocky
    Martin Bodocky about 9 years
    I should say it doesn't work for me, let t = ref None t := Some(context.Items.FirstOrDefault(fun ii -> ii.Name = i.Name)) match !t with | Some it -> - finished here even it is null | None -> ignore
  • Rune FS
    Rune FS over 4 years
    @MartinBodocky your code will always return Some(_). It either returns Some(value) or Some(defaultof<>) both will match the Some _ case in your match expression. you could use context.Items |> Seq.tryFind(fun II -> ii.Name = i.Name) then the match expression would work as you expect