Professional Development – 2024 – Week 32

Image Credit: https://www.flickr.com/photos/54585499@N04/

.NET

The New Option and Result Types in C# (via Nick Chapsas)

  • Using exceptions to control the flow of execution — for example, throwing exceptions for invalid model states — is very slow and a bad practice.
  • There’s a new Option<T> type that will be either T or have no type. (This sounds very similar to the OneOf NuGet package.) This will force you to deal with both scenarios, unlike if a type is nullable where it’s only a compiler warning if you don’t null-check first. There is some syntactic sugar (just like with Task<T>) such that you just return the type instead of an Option<T>. To return a failed state, create a new Option<T> using the constructor that accepts an exception.
  • To process the results, use the .Match() method via LanguageExtensions. (This will eventually turn into a switch statement.) There’s also .IsSome() or .IsNone().
  • Result<T> gives you similar functionality for success and failure.