What is the equivalent in F# of the C# default keyword?
C#F#DefaultKeywordC# to-F#C# Problem Overview
I'm looking for the equivalent of C# default
keyword, e.g:
public T GetNext()
{
T temp = default(T);
...
Thanks
C# Solutions
Solution 1 - C#
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
Solution 2 - C#
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#.