Is there a safe way to declare a string variable in visual basic?
When working with PHP, I have always declared my string variable and set them to zero to be safe. I'm new to visual basic and I'm wondering what is the safest way to declare a string variable. Will it
Dim strWords As String
enough? Or is it better to set to null or nothing or some other default or primitive type?
source to share
By default, strWords will be the default Nothing
.
Instead of guaranteeing that this value is never nothing by setting a value when you declare a variable, you must ensure that your code leaves no room for it to strWords
be Nothing, and if so, it must be handled.
If you need to check if a string is empty or nothing, you can do:
If Not String.IsNullOrEmpty(strWords) Then
source to share
The best way to declare a string variable is to set it to an empty string immediately after the declaration. For most .NET developers, it is a common mistake to set a string to "or Nothing. This is incorrect, because" "is not really an empty string for the .NET CLR, and nothing can throw a NullReferenceException if you reference the string later in The following is the correct code to declare a string:
Dim str As String = "" ' <--This is "not best practice"
Dim str2 As String = Nothing ' <--This is "not best practice"
Dim str3 As String = vbNullString ' <--This is "not best practice"
Dim str4 As String = String.Empty ' <--correct
source to share