Determine empty column with Nothing, = Nothing or IsNullOrEmpty
-
27-06-2021 - |
Pregunta
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:
If customerRegion = "" Then
If customerRegion = Nothing Then
If String.IsNullOrEmpty(customerRegion) Then
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
Solución
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 beNothing
. If the column value was null, it would equalDBNull
, notNothing
.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 equalsNothing
, VB.NET automatically considersNothing
to be an empty string. That is why it evaluates to True.If String.IsNullOrEmpty(customerRegion) Then
- This will work well, but it's unnecessary since the column value will never be null (Nothing
) (see #1).If customerRegion Is Nothing Then
- This will never return true (see #1).
Otros consejos
- No, they are not the same. The #2 will return
True
if the value is actuallyNothing
. 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 notNothing
.There is another check that you can do:
IsNullOrWhitespace
. But if you need to detect specifically strings of zero length, you should compare them toString.Empty
.
Like this:
If customerRegion = String.Empty Then