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:
because this is just the same as
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 toNothing
A blank string (
""
) andString.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:String.Empty
produces:So to answer your question:
So you should be using the following if you want an empty string
And the following if you want a Null (Nothing) string:
Which one you want depends on what you are doing