Wednesday, August 30, 2017

C# Tip: A custom ThrowIf generic class

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.

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:
Throw<Exception>.If(someCondition, "Some Exception");

Way cleaner, right? Let's see how to implement such a class.

Throw<>.If

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:

Conclusion

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