Link to home
Start Free TrialLog in
Avatar of Mr_Fulano
Mr_FulanoFlag for United States of America

asked on

Nothing vs String.Empty

Hi, I'm using VB 2005, WinForms. I have a question about initializing variables and setting their value from a best practices point of view.

Let say I have a String variable called "strMyString" and I want to initialize its value to "No Value".

What is the best way to accomplish this, so that I can avoid problems in my code with DBNulls later at runtime.

Which of the following would be better -- or does it make a difference.

Dim strMyString as String = Nothing
or
Dim strMyString as String = String.Empty
or
Dim strMyString as String = ""

Is there a better way?

Thanks for your help,
Fulano
Avatar of Jorge Paulino
Jorge Paulino
Flag of Portugal image

Hi Mr_Fulano,

String.Empty or "" is the same but  you type " " (with a space in the middle) and cause you problems. Nothing is used for objects and not string.

I always use String.Empty

Avatar of Mr_Fulano

ASKER

Hi JPaulino, nice to hear from you...

Interesting...I didn't know that Nothing was limited to Objects. It works for Strings, but lately I've begun to get a little worried that I'm using it too often.

Thanks for the input!
Fulano
Indeed a string can be Nothing because it is a reference type.
I think the best equivalence to DbNull is Nothing.
String.Empty is a string that is empty (zero-length) but it is not Nothing

to elaborate a bit more, it is not the same:

UPDATE SOMETABLE SET SOMEFIELD = ''      (can be represented by String.Empty)

than

UPDATE SOMETABLE SET SOMEFIELD = NULL    (can be represented by Nothing)
Hi Jaime,

OK, so let me see if I understand your perspective. -- Are you saying that it is better to use Nothing to avoid a DBNull, or that if you use Nothing, you almost guarantee yourself a DBNull?

Thanks,
Fulano
SOLUTION
Avatar of Jaime Olivares
Jaime Olivares
Flag of Peru image

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
SOLUTION
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
ASKER CERTIFIED SOLUTION
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
also consider this:

Dim value as DbNull
Dim myString as String = value.ToString()     ' will return you an empty (not null) string
All very good advice and I learn a few things along the way. I thank you all for your suggestions and believe that a split of the points is equitable, given all the on-point suggestions made.

Thanks,
Fulano