mike-obrien.net Curriculum Vitae Blog Labs
Wednesday, January 03, 2007

I really have to remember to use the IsNullOrEmpty method in the string class. I keep forgetting to use it so I figure if I blog about it I'll remember.. ;)

// Why do this...
if (MyString != null && MyString.Length > 0) {...}

// When you could do this???
if (string.IsNullOrEmpty(MyString) == false) {...}

And while we are on the subject, the .NET framework defines a lot of nice constants for us to use instead of defining our own or using literals. See if one exists in a class near you... Here are a couple of examples:

// Why use the "" literal when you can use
String.Empty;

// = "\"
System.IO.Path.DirectorySeparatorChar;

// = "/"
System.IO.Path.AltDirectorySeparatorChar;

// Returns char[] {'"', ...}
System.IO.Path.GetInvalidPathChars();

// Returns char[] {'"', ...}
System.IO.Path.GetInvalidFileNameChars();

.NET | C# | VB.NET