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.




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Different Stages of Data/AI Product Development

My daughter was a creative genius, and then we bought her an iPhone Stephanie Gruner Buckley…

Presearch Weekly Update #69 — May 27, 2022

STM32 Flash Programming

Top 5 Key Advantages of Laravel Application Development for Website

Create popup background with an anchor in the Android Kotlin

Using PyCharm to Become a Professional Python Programmer Part 1

How to clear Google Drive cache

Google Drive logo

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
Achraf Chennan

Achraf Chennan

More from Medium

C# Understanding Interfaces + simple mocking + testing (xUnit + NSubstitute)

MongoDB C# Driver, clean and manageable database queries using dynamic predicates.

Keyed Dependency Injection using .NET

Garbage Collection in .NET