Updated January 2024
String validation is a widespread practice when evaluating user input or data received from API requests. In the course of my code reviews, I often come across situations where developers persist in using the following code to ascertain if a string variable contains a value.
if (emailAddress == "")
This could potentially pose a performance issue and might lead to an exception later on if the string is null. The more efficient and exception-resistant approach is to utilize one of the following methods from the String
type:
- IsNullOrEmpty(): Introduced in the .NET Framework 2.0
- IsNullOrWhiteSpace(): Introduced in the .NET Framework 4.0
Here is an illustrative example.
if (string.IsNullOrEmpty(emailAddress))
Both methods return a Boolean value, and, notably, they will never result in an exception. Here are alternative approaches that developers commonly use to check for an empty string.
if (emailAddress?.Length == 0)
or
if (emailAddress == null || emailAddress == string.Empty)
or pattern matching can also be used:
if (emailAddress is { Length: > 0 })
Benchmark
From the results, it is evident that employing IsNullOrEmpty()
is more efficient than other methods for checking an empty string.
When I setup the code analysis in my EditorConfig it looks like this: dotnet_diagnostic.CA1820.severity = warning
Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks
Make a one-time donation
Make a monthly donation
Make a yearly donation
Choose an amount
Or enter a custom amount
Your contribution is appreciated.
Your contribution is appreciated.
Your contribution is appreciated.
DonateDonate monthlyDonate yearlyIf you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave
© The information in this article is copywritten and cannot be preproduced in any way without express permission from David McCarter.