Welcome to the 88th edition of The Catch Block, and to 2022! Here's hoping this third edition of 2020 is better than the previous two.
In this edition, I show off a bit by showing some of my favorite mini-extension methods; that is, small methods that do just a tiny bit of functionality that I use often.
Plus: refactoring C# 10, resolutions, EF 6 to EF Core, and creativity powered by music. Let's get going!
Cool C# Mini-Extensions
I'm a big fan of writing extension methods in C# to make my code more readable, and to encapsulate functionality I'll be using quite a bit. For this first edition of 2022, I thought I'd share some of my favorite C# extensions that my team and I have been using in the last year.
Removing Last Instance of a Word in a String
Because I like to use Dapper a lot, I often have to construct complicated SQL queries, and many times I end up with extraneous operators at the end of the query. For example, one of my complicated queries might end with an extra AND that I need to remove.
Note that this extension will remove the removeToken AND anything that follows it from the targetString.
Getting the End of the Day
Sometimes, for time range calculations, I really need to get the time "end" of a particular date. So, instead of getting January 2nd, 12:00:00 AM, I need to get January 1st, 11:59:59 PM. I can do that with this tiny extension:
public static DateTime EndOfDay(this DateTime date)
Displaying a Nullable Boolean as Yes/No/NA
Since my team primarily works on internal business applications, we often have situations where we are using a boolean to represent a "yes or no" selection. So we coded up a tiny extension to display a nullable boolean as "yes", "no", or "N/A".
public static string AsYesNo(this bool? value)
if (value.HasValue && value.Value == true)
else if (value.HasValue && value.Value == false)
else return "N/A";
We use this extension primarily on CSHTML views, like so:
<th>Is this a recurring issue?</th>
This article is for paying subscribers only
Sign up now and upgrade your account to read the article and get access to the full library of articles for paying subscribers only.