![]() ![]() Starting with the fact that we’re declaring Optional as a struct instead of a class, there are two main reasons. Too many times we seem to avoid creating new types when it’s a great way to make our code more expressive. Regardless of complexity though, I’d say just the fact that we use a type to represent the possible absence of value is the important part. Internal Optional(T value, bool hasValue)Īs you can see from the size alone, really not that much going on. I’ll drop the code right now, so we can go through it afterwards. We’ll put it in a Shared folder inside the Domain project, just for simplicity, but it should probably be extracted to a different project, as it’s a very generic concept, not tied to the domain logic. Let’s begin by creating a simple implementation of an Optional type. We’ll continue using the group management project to play around with these concepts. Optional or Functional Extensions for C#) We’ll implement a simple version of an Optional type, to understand what’s going on, but there are some NuGet packages already available, so you might be interested in checking them out (e.g. In this episode, we’ll explore using such a type instead of relying on null. ![]() The goal of using an Optional type is twofold: not only it makes the absence of value explicit, forcing us to deal with it, as in C# is far from impossible to forget the null check, but with some auxiliary methods, we can sometimes even bypass checking for the existence of value, instead writing more linear code, following some functional programming principles. Some other languages, particularly functional languages, use a different approach to represent the absence of a value.Ī popular (and safer) approach to representing the possibility of a value not being present is to use a specific type to represent it, like an Optional type, also known as Option or Maybe, depending on the language. One of the things that more often catches us by surprise is the NullReferenceException, not only in C#, but also in other similar languages. The playlist for the whole series is here. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |