89

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

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

Thanks

elmattic
  • 12,046
  • 5
  • 43
  • 79

2 Answers2

100

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>
Brian
  • 117,631
  • 17
  • 236
  • 300
blu
  • 12,905
  • 20
  • 70
  • 106
39

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

Józef Podlecki
  • 10,453
  • 5
  • 24
  • 50
Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553
  • 1
    In your C# example, you use an assignment operator instead of an equality operator inside the if statement. Is that deliberate? – doppelgreener Oct 14 '13 at 05:03
  • 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 – Martin Bodocky Jan 20 '15 at 15:00
  • @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 – Rune FS Nov 04 '19 at 13:21