.net – which is the best way to initialize a string with null in vb.net

initializationnetstringvb.net

We can declare and initialize a string variable in vb.net in following ways:

 Dim str1 As String = ""
 Dim str2 As String = Nothing
 Dim str3 As String = vbNullString

Question :

  • Which one is the best programming practice?
  • What is the difference between these three methods?

Best Answer

A string will be set to Nothing until you specify otherwise, so there is no need to initialise it like this:

Dim s As String = Nothing 

because this is just the same as

Dim s As String

You may want to set it Nothing later on in your code but not at initialisation,

vbNullString is a carry over from VB6 days and is functionally equivalent to Nothing

A blank string ("") and String.Empty are equivalent.


Some say String.Empty has a slight performance advantage but I don't see any evidence.

Note: The IL produced by these two is different:

"" produces:

IL_0001:  ldstr      ""

String.Empty produces:

IL_0001:  ldsfld     string [mscorlib]System.String::Empty

So to answer your question:

Dim str1 As String = "" 'Initialises as blank string same as String.Empty
Dim str2 As String = Nothing 'Same as Dim str2 As String
Dim str3 As String = vbNullString 'Same as previous line but deprecated so avoid

So you should be using the following if you want an empty string

Dim s As String = ""

And the following if you want a Null (Nothing) string:

Dim s As String

Which one you want depends on what you are doing