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 new Exception("Some exception");
}
Throw<Exception>.If(someCondition, "Some Exception");
Throw<>.If
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:Conclusion
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
- My journey to 1 million articles read
- Adding Application Insights to your ASP.NET Core website
- Send emails from ASP.NET Core websites using SendGrid and Azure
- Creating ASP.NET Core websites with Docker
- Hosting NuGet packages on GitHub
- Configuration in .NET Core console applications
- Package Management in .NET Core
- Exporting HTML to PDFs 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
- Generating views in the backend with ASP.NET
- Testing JavaScript on ASP.NET Core Applications