C# 3.5 partial class String IsNullOrWhiteSpace

Viewed 12434

I'm trying to create extra functionality to the String class (IsNullOrWhitespace as in .NET4 ) But I'm having an problem with referencing:

Error 1 'String' is an ambiguous reference between 'string' and 'geolis_export.Classes.String'

I don't want to create an extension method. Because this will crash if string x = null;

Usage:

private void tbCabineNum_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    e.Handled = !e.Text.All(Char.IsNumber) || String.IsNullOrWhiteSpace(e.Text);
}

String partial:

public partial class String
{
    public static bool IsNullOrWhiteSpace(string value)
    {
        if (value == null) return true;
        return string.IsNullOrEmpty(value.Trim());
    }
}

Is it not possible to create extras for the String class? I have tried to put the partial in the System namespace, but this gives other errors.

Renaming String to String2 fixes the problem also. But this is not what I want, because then there is no reference with the original String class.

7 Answers

Trimming the string results in an avoidable string allocation (which can hurt performance). Better to check each character in turn and not allocate anything:

        public static bool IsNullOrWhiteSpace(this string value)
        {
#if NET35
            if (value == null)
                return true;

            foreach (var c in value)
            {
                if (!char.IsWhiteSpace(c))
                {
                    return false;
                }
            }

            return true;
#else
            return string.IsNullOrWhiteSpace(value);
#endif
        }

The #if NET35 code means that the fallback implementation exists only when targeting .NET 3.5. You can adjust that comparison to meet your project's target frameworks as needed. Otherwise, the default string.IsNullOrWhiteSpace method is used, and this util method would likely be inlined.

Related