Link to home
Start Free TrialLog in
Avatar of lapucca
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.
ASKER CERTIFIED SOLUTION
Avatar of p_davis
p_davis

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of lapucca
lapucca

ASKER

Perfect!  Thank you.
As p_davis said:
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;
		}
	}
}

Open in new window

Which produces the following output -User generated image***NOTE***
IsNullOrWhiteSpace is native in .NET 4 and above, it has to be implemented in .NET 3.5 and below.

-saige-
Avatar of lapucca

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.