Power Enums Option type but for csharp
Let’s talk about PowerEnums. A new C# library that I started cooking yesterday.
It’s been over a year since I started writing Rust and I found it an intriguing language. Besides the promises of top-notch performance and fearless concurrency, I also found rust to be an easy-to-learn systems language for me. This is coming from me who had a bit of flirt with C while in the university.
One of rust’s main selling point for me is how clear and easy the type system is. You have a straightforward type system, generics, pattern matching (which I love so much) and traits. All of these I was able to learn in a bit of time and the ease at which I was able to pick up rust was surprising to me. Rust for me is just like python but with extra invincibility of systems languages like C and C++. It’s almost as powerful (if not as powerful) as C and C++ and it has plain old english-like syntax like python. Oh and rust’s getting into both the windows and linux kernel already which is a W for me.
Now to the main theme of this article, Option enum type in rust is an enum type in the rust standard library that gives us the idea of optional values. That is, value types can be seen in a basis of whether they are present or absent - present as in Some(T) or absent as in None. This is in fact rust’s intuitive way of prevent Null-Reference exceptions and allied problems in contrast to C# which I have been used to and written for over 7 years already. This means that Option in C# would make us have less of ‘ObjectReferenceException: Object Reference Not Set to An Instance of an Object’ - every C# developer has probably seen this countless number of times.
In Rust, an Option<T> defines an optional type in which the enclosed generic type could be any data type from primitives to reference types. The Option<T> type in rust could be matched with pattern machine to create more elegant control flow. It can be combined with other constructs like If-Let, Match and While let all of which allow for destructuring of the optional into Some(T).
See below:
With match expression
With if-let
With while-let
C# implementation
The C# implementation that I’ve just made is quite similar, we have an Option<T> type which can enclose the value of interest into either of a Some(T) or None(T). I call it PowerEnums and it’s already published to nuget.org as a .NET C# library.
See the code references below:
Simple Option - Some<T>
Simple Option - None<T>
Option-returning methods Option<T>
Option<T>().ValueOrError() with error message
Option<T>().ValueOrError() with error callback
Check IsSome() or IsNone()