About Nothing

Sometimes in your code you will need to check to see if a value is nothing/null or not. In .NET there are many different ways to check for this condition. It can also be different depending on the language you use. These little differences can really bite you in the a**, so you need to be aware of the differences.

I like to use the IsNullOrEmpty() method on the string class, so let's take a look at this method using C#.

private void TestNullOrEmpty()
{
  string value;

  //Debug.WriteLine(String.IsNullOrEmpty (value));   // NOT VALID

  Value = null;

  Debug.WriteLine(String.IsNullOrEmpty(value));

  Value = "Hello There";

  Debug.WriteLine(String.IsNullOrEmpty(value));

  if (value != null)
    Debug.WriteLine("NOT null");
}

In C# the first check of the Value variable is not valid since the string has not been initialized.

In VB.NET you can also use IsNullOrEmpty() method, however, the first check is valid since VB.NET treats this type of error as a warning only. You can change this setting in the Project Settings for your project, so this would be a real error. You can also use the new IsNothing statement to check to see if a value is Not Nothing.

Private Sub TestNullEmpty()
  Dim value As String

  Debug.WriteLine(String.IsNullOrEmpty(value))

  value = Nothing

  Debug.WriteLine(String.IsNullOrEmpty(value))

  value = "Hello There"

  Debug.WriteLine(String.IsNullOrEmpty(value))

  If value IsNot Nothing Then
    Debug.WriteLine("NOT Nothing")
  End If
End Sub

I hope this helps someone in the future when you are moving from one language to another.

Good Luck With Your Coding,
Paul Sheriff

** SPECIAL OFFER FOR MY BLOG READERS **
Visit http://www.pdsa.com/Event/Blog for a free eBook on "Fundamentals of N-Tier".

Past Blog Content

Blog Archive

No Comments