lapucca
asked on
Testing fro null or empty string
I know this is a basic C# question but I cannot remember the answer.
If I want to test for the string condition before processing can I use
var strTest = null;
if(strTest == null || strTest.trim() == string.Empty)
....
Of do I have to break them up like
if(strTest == null)
return;
if(strTest.trim() != string.Empty)
Do something here......
Thank you.
If I want to test for the string condition before processing can I use
var strTest = null;
if(strTest == null || strTest.trim() == string.Empty)
....
Of do I have to break them up like
if(strTest == null)
return;
if(strTest.trim() != string.Empty)
Do something here......
Thank you.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
As p_davis said:
IsNullOrWhiteSpace is native in .NET 4 and above, it has to be implemented in .NET 3.5 and below.
-saige-
using System;
namespace EE_Q28702578
{
class Program
{
static string s1 = default(string); // Null string
static string s2 = ""; // Empty string
static string s3 = " "; // Whitespace string - technically not empty
static string s4 = "Unempty string"; // Self explanatory
static void Main(string[] args)
{
if (s1.IsNullOrWhiteSpace())
Console.WriteLine("s1 is a null or whitespace string.");
else
Console.WriteLine("s1 is not a null or whitespace string.");
if (s2.IsNullOrWhiteSpace())
Console.WriteLine("s2 is a null or whitespace string.");
else
Console.WriteLine("s2 is not a null or whitespace string.");
if (s3.IsNullOrWhiteSpace())
Console.WriteLine("s3 is a null or whitespace string.");
else
Console.WriteLine("s3 is not a null or whitespace string.");
if (s4.IsNullOrWhiteSpace())
Console.WriteLine("s4 is a null or whitespace string.");
else
Console.WriteLine("s4 is not a null or whitespace string.");
Console.ReadLine();
}
}
static class Extensions
{
// We have to implement this prior to .NET 4...
public static bool IsNullOrWhiteSpace(this string source)
{
return string.IsNullOrEmpty(source) || source.Trim().Length == 0;
}
}
}
Which produces the following output -***NOTE***IsNullOrWhiteSpace is native in .NET 4 and above, it has to be implemented in .NET 3.5 and below.
-saige-
ASKER
Thank you Saige,
I forgot to mention I'm using .net 4.5 so it works for me. Thank you for the reply. I'm sorry that I already give points away but I will mark yours as good comment.
I forgot to mention I'm using .net 4.5 so it works for me. Thank you for the reply. I'm sorry that I already give points away but I will mark yours as good comment.
ASKER