Wednesday, August 30, 2017

ThrowIf - Throwing exceptions elegantly in .NET with generics and C#

The C# generics feature simplifies a lot our code. Let's see how to leverage it to thrown exceptions elegantly.
C# Generics makes it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. It's a very useful way to improving readability, reduce duplication of your code, simplify common tasks and my favorite: make code cleaner. In other words, make your code SOLID and DRY.

In this post, let's design a generic exception class to  simplify how we throw exceptions.

Throwing Exceptions

Usually, we write code like this repeatedly, which's usually a candidate for a DRY refactoring:
if (someCondition){
   throw new Exception("Some exception");
But what if we could write this as a one-liner. Way cleaner, right? Let's see how to implement such a class.
Throw<Exception>.If(someCondition, "Some Exception");


The Throw<>.If class is a generic class that allows trowing exceptions without repeating ifs/throws in the code:

Using Throw<>.If

So with our generic ThrowIf class we could do:


C# Generics is pretty powerful feature of C# and worth understanding well. As seen on this example, we can leverage to significantly improve and enhance the readability of our code and avoid repetition.

See Also

About the Author

Bruno Hildenbrand      
Solutions Architect, Software Engineer and open-source enthusiast.
.NET, Azure, Go, Linux, Vim, Fedora, i3, Development and Architecture.