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.

Example 1 the non-generic class
Example 2 the generic class

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.

Example 3 returning an instance of Result class

In the second example below I check if the result is successful else I display the error.

Example 4 reading the value from the Result class

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.

Wrapping up

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.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store