Wednesday, August 30, 2017

C# Tip: A custom ThrowIf generic class

The C# generics feature makes it possible to extend and simplify code. Let's see how we can use them to control exceptions.
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 take a look in how we can utilize generics to design a generic exception class to  simplify throwing 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 helps us trowing exceptions without repeating ifs/throws in our codebase:

Using Throw<>.If

So with our generic ThrowIf class we could do:


The C# Generics feature exists for quite a long time but it's pretty powerful and a feature worth understanding well. Utilizing it significantly improves and enhances the readability of our code.

See Also

Why you should start using .Net Core
Package Management in .Net Core
Exporting Html to Pdf using only JavaScript
Importing CSVs with .Net Core and C#
Exporting a CSV generated in-memory in Asp.Net with C#
Building and Running Asp.Net Core apps on Linux
Asp.Net / Asp.Net Core: Generating views in the backend
Testing Javascript on Asp.Net Core Applications