Using the result class in C#
What is the Result class?
The Result class is a way to handle returning results to the presentation layer. I learned it from a great tutorial of Vladimir Khorikov on Pluralsight. The implementation is very simple and it cleans up a lot of dirty code.
Why use it?
Often I found myself inconsistently handling errors, null value’s etcetera. With the Result class, you can create a clear and consistent workflow for returning values between layers or methods.
How to implement it
We divine a class named Result and a generic class of Result<T>. The constructor needs to be protected. After that define the methods and properties in examples 1 and 2.
How to use it
In the example below I request a list of Todo items. I do a null check, if the object is null I return a Result class with an error label filled in.
In the second example below I check if the result is successful else I display the error.
The main advantage you have with this approach is that you have consistency in communication between your presentation layer, in this case, a WPF application and your business layer.
You can check out a full example on my Github. The link is in the section at the end. You also find a link to an article from Vladimir and the link to the course on Pluralsight.
- Github example: https://github.com/achraf1996/SimpleTodoList
- Article on functional programming: https://enterprisecraftsmanship.com/posts/functional-c-handling-failures-input-errors/
- Course on functional programming: https://app.pluralsight.com/library/courses/csharp-applying-functional-principles/table-of-contents