Alex Rivera | Logout

C# 3.5 partial class String IsNullOrWhiteSpace

Asked 2011-06-30T13:28:28.250
15

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.

Edit
Report

2 Answers

2

The string class is not declared as partial, you will have to write an extension method instead.

answered 2011-06-30T13:30:50.763
0

In order to create an extension method, you need to use the following syntax. (Note the use of the keyword this):

public static bool IsNullOrWhiteSpace(this string value)
answered 2011-06-30T13:30:37.660

Your Answer