Convenient Uses of C# Extension Methods - Part 2
In this article I'll discuss another way I've made my life easier with C# extension methods. In A Convenient Use of C# Extension Methods - Part 1", I showed how an extension method can be used to conveniently display a user-friendly version of an enumerated type.
Over the years, I've built up a number of libraries that I tend to use in any project I work with. In one such library, I have a couple of extension methods for strings to make my code easier to read and maintain.
When it comes to strings, I hate checking for null or empty / whitespace this way:
var inputValidator = new InputValidator(); var userComment = GetUserComment(); var sanitizedComment = inputValidator.SanitizeComment(userComment); if (string.IsNullOrEmpty(sanitizedComment) == false) { // do something with this valid comment.... }
When I see code like the highlighted line above, I have to think for a few seconds to make sure I know what the conditional is really checking. This slows me down when scanning or debugging code.
So, I have a couple of extension methods that make the code more readable.
public static class StringExtensions { public static bool HasValue(this string source) { return (!source.IsEmpty()); } public static bool IsEmpty(this string source) { return (string.IsNullOrWhiteSpace(source)); } }
With these extensions in scope, we can now do this:
if (sanitizedComment.HasValue()) { // do something with this comment.... }
A similar case exists when trying to Trim() a string or get its Length(). These methods will fail if the strings are null. With a few extension methods, we can automatically handle the null when we call the methods:
public static class StringExtensions { public static string SafeTrim(this string source) { return (source == null) ? "" : source.Trim()); } public static int SafeLength(this string source) { return (source == null) ? 0 : source.Length; } }
With those extension methods in scope, we can write code like this:
if (newComment.SafeLength() > MaxExcerptLength) { // do something with comment } var trimmedComment = newComment.SafeTrim();
As you can see, with a very little amount of work, the code is cleaner and more readable.