An option type in C#




esther.machata@gmail.com - @stuckinadrawer

what's an option type?

generic type that can encapsulate an optional value

may or may not contain a value

useful as return value for function

why would I use that?

avoid NullReferenceExceptions

signal intent and model your data more explictly

focus on your domain by cutting down on manual null checks

Option in F#


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"

What about null and nullable?

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

null and type safety


string s1 = "abc";
var len1 = s1.Length;

string s2 = null;
var len2 = s2.Length;
						

This will explode!

null vs missing data

completely different concepts!

null is often (ab)used to represent missing/optional data

But we already have Nullable!

only works on value types

no special behavior

Null checking is so easy!


string s1 = null;
var length = s1 != null ? s1.length : 0;
var length = s1?.length ?? 0;
							

You're screwed if you forget to use it!

Option to the rescue!

Get the type system to help you

C# doesn't have an option type though?

No, but smart people built one!

https://github.com/nlkl/Optional

Optional

  • Provides Maybe and Either
  • 'Unsafe' access to value only with different namespace import
  • Option type treated like collection: map, filter

Demo time!

Railway oriented programming

Talk by Scott Wlaschin

Conclusion

It’s not that dealing with any given instance of null is particularly hard, it’s that it is so easy to miss one.

Thank you!

Questions?




esther.machata@gmail.com - @stuckinadrawer