mroyer
mroyer

Reputation: 55

Valid null returns and warnings in C#

I am updating very old code to VS2022. Some of the string extension functions return null and VS2022 flags this with a warning. What is the modern recommended or accepted method to handle this to eliminate the warnings?

As you can see in the example below, the null is returned if (and only if) the original string was null. In some sense, this is a proper handling. That said, should we suppress the warning in VS, but risk missing valid warnings of null returns in other places? Or, should we change the behavior of the original code to return something else besides null, such as an empty string. Or, we could just live with the benign warnings... but I hate left-over, benign warnings. They are noise and can obscure real issues.

Opinions, thoughts, what is the recommended way to proceed?

        /// <summary>
        /// Returns a new string with multiple, contiguous embedded spaces and tabs reduced to a single space
        /// and single embedded tabs converted to spaces
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string MultipleSpacesToOneSpace(this string str) {
            if ( str == null ) return null;
            var len = str.Length;
            var src = str.ToCharArray();
            int dstIdx = 0;
            bool lastWasWS = false;
            for (int i = 0; i < len; i++) {
                var ch = src[i];
                if (src[i] == '\u0020' || src[i] == '\u0009') {  // spaces and tabs
                    if (lastWasWS == false) {
                        src[dstIdx++] = ch;
                        lastWasWS = true;
                    }
                } else {
                    lastWasWS = false;
                    src[dstIdx++] = ch;
                }
            }

            string newStr = new string(src, 0, dstIdx);
            return newStr.Replace('\u0009', '\u0020');  // replace tabs with spaces
        }        

-Mark R.

Upvotes: 0

Views: 108

Answers (2)

Leon Bohmann
Leon Bohmann

Reputation: 402

For further explanation of my comment and using @Dimitry Bychencko s answer you could come up with:

public static string? MultipleSpacesToOneSpace(this string? input){
    if (input == null) return null;
    
    return ((string)input).MultipleSpacesToOneSpace();
}

And then remove the first line from your original method.

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186813

I suggest to forgive nulls with a help of ! operator:

...
if ( str == null ) return null!;
...

You can also simplify the implementation with a help of regular expressions:

using System.Text.RegularExpressions;

...

public static string MultipleSpacesToOneSpace(this string str) =>
  str != null ? Regex.Replace(str, @"\s+", " ") : null!;

here we match all consequent whitespaces (tabs, spaces, non breaking spaces etc.) and replace them with single space. And again, we forgive null returning with null!.

Upvotes: 2

Related Questions