generic type that can encapsulate an optional value
may or may not contain a value
useful as return value for function
avoid NullReferenceExceptions
signal intent and model your data more explictly
focus on your domain by cutting down on manual null checks
type Option<'a> =
| Some of 'a
| None
let validInt = Some 1
let invalidInt = None
match validInt with
| Some x -> printfn "the valid value is %A" x
| None -> printfn "the value is None"
So, what exactly is null again? Per MSDN:
“The null keyword is a literal that represents a null reference, one that does not refer to any object.”
string s1 = "abc";
var len1 = s1.Length;
string s2 = null;
var len2 = s2.Length;
This will explode!
completely different concepts!
null is often (ab)used to represent missing/optional data
only works on value types
no special behavior
string s1 = null;
var length = s1 != null ? s1.length : 0;
var length = s1?.length ?? 0;
You're screwed if you forget to use it!
Get the type system to help you
No, but smart people built one!
It’s not that dealing with any given instance of null is particularly hard, it’s that it is so easy to miss one.