Home > Refactorings > Refactorings that work with strings – Use IsNullOrEmpty

Refactorings that work with strings – Use IsNullOrEmpty

November 25th, 2011

When checking that a user has provided a valid input, you will often want to ensure that it is not null or empty. Strings are reference types and can be equal to a null value like any other reference type. Strings can also be empty, meaning their values equal “” and they have zero length. The IsNullOrEmpty call of the System.String class indicates whether the given string is a null or an empty (“”) string. Before this call appeared in the .NET Framework, we were checking strings as follows (for example):

Refactorings - Use IsNullOrEmpty sample code

This code checks the userName, password and domainName strings that are null and uses different checks for the string contents. All these checks can be replaced with the corresponding IsNullOrEmpty call in by applying the Use IsNullOrEmpty refactoring. The Use IsNullOrEmpty refactoring shipped in DevExpress Refactor! Pro allows you to convert the string checking code into the appropriate call in a single step:

Refactorings - Use IsNullOrEmpty preview

The result produced is now much more readable:

Refactorings - Use IsNullOrEmpty result

If you don’t want to replace all checks, you can select those to be converted:

Refactorings - Use IsNullOrEmpty partial preview

Only selected checks will be replaced by the refactoring:

Refactorings - Use IsNullOrEmpty partial result

The refactoring requires both checks (for null and empty) to occur at once. Strings can be either equal to the null literal, meaning they don’t reference any data, or empty, meaning they reference a character buffer that is zero characters long. IsNullOrEmpty call detects both of these conditions at the same time.

However, this refactoring also has a second version that does not require thes both conditions simultaneously. This version is implemented as a code provider operation which may change the program behavior. The Use IsNullOrEmpty code provider allows you to replace one of the checks to the String.IsNullOrEmpty call:

Use IsNullOrEmpty code provider preview

Use this code provider when you are sure that you need both checks made for a string, otherwise it may change the logic of the code – e.g. when you cannot have a null string value, but you can have an empty string value.

Also, refer to other refactorings that work with strings.

—–
Products: Refactor! Pro
Versions: 11.1 and up
VS IDEs: any
Updated: Dec/02/2011
ID: R045

Similar Posts: