Question

When you want to determine if a database column is empty (i.e not null but there is not any value in it) what are the differences between the below options:

customerRegion varchar(10) NULL is retrieved from the SQL database:

  1. If customerRegion = "" Then
  2. If customerRegion = Nothing Then
  3. If String.IsNullOrEmpty(customerRegion) Then
  4. If customerRegion Is Nothing Then

1,2,3 returns True 4 returns False when the column is empty.

Is 1 and 2 technically the same thing? and Why is 4 returning False?

Out of 1,2 and 3 which one should be used to determine if the column is empty (or is there any other way of doing it)?

Thanks

Was it helpful?

Solution

  1. If customerRegion = "" Then - This tests to see if the column contains an empty (0 length) string. This is the "best" option because the value will never be Nothing. If the column value was null, it would equal DBNull, not Nothing.
  2. If customerRegion = Nothing Then - This is very confusing because many people will think it's interchangeable with #4 (Is Nothing). When you test if a string equals Nothing, VB.NET automatically considers Nothing to be an empty string. That is why it evaluates to True.
  3. If String.IsNullOrEmpty(customerRegion) Then - This will work well, but it's unnecessary since the column value will never be null (Nothing) (see #1).
  4. If customerRegion Is Nothing Then - This will never return true (see #1).

OTHER TIPS

  • No, they are not the same. The #2 will return True if the value is actually Nothing. From the documentation:

For strings in Visual Basic, the empty string equals Nothing. Therefore, "" = Nothing is true.

So the behavior has to do with VB-specific handling of = Nothing with strings.

  • Number 4 returns False because the string is empty, but it is not Nothing.

  • There is another check that you can do: IsNullOrWhitespace. But if you need to detect specifically strings of zero length, you should compare them to String.Empty.

Like this:

If customerRegion = String.Empty Then
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top