I define a string and check it by string.IsNullOrEmptyOrWhiteSpace()
.
But I got this error:
'string' does not contain a definition for 'IsNullOrEmptyOrWhiteSpace' and no extension method 'IsNullOrEmptyOrWhiteSpace' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) D:\project\project\Controllers\aController.cs 23 24 project
What is the reason?
String.IsNullOrWhiteSpace has been introduced in .NET 4. If you are not targeting .NET 4 you could easily write your own:
public static class StringExtensions
{
public static bool IsNullOrWhiteSpace(string value)
{
if (value != null)
{
for (int i = 0; i < value.Length; i++)
{
if (!char.IsWhiteSpace(value[i]))
{
return false;
}
}
}
return true;
}
}
which could be used like this:
bool isNullOrWhiteSpace = StringExtensions.IsNullOrWhiteSpace("foo bar");
or as an extension method if you prefer:
public static class StringExtensions
{
public static bool IsNullOrWhiteSpace(this string value)
{
if (value != null)
{
for (int i = 0; i < value.Length; i++)
{
if (!char.IsWhiteSpace(value[i]))
{
return false;
}
}
}
return true;
}
}
which allows you to use it directly:
bool isNullOrWhiteSpace = "foo bar".IsNullOrWhiteSpace();
For the extension method to work make sure that the namespace in which the StringExtensions
static class has been defined is in scope.
Here's another alternative implementation, just for fun. It probably wouldn't perform as well as Darin's, but it's a nice example of LINQ:
public static class StringExtensions
{
public static bool IsNullOrWhiteSpace(this string value)
{
return value == null || value.All(char.IsWhiteSpace);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With