0

When working with PHP I always declared my string variable and set them equal to null just to be safe. I'm new to visual basic and am wondering what the safest way to declare a string variable is. Will

Dim strWords As String

be sufficient? Or is it better to set it to null or nothing or some other default value or primitive type?

2
  • Yes, from what I could tell. (But then I am a beginner, so take my advice with half a grain of salt worth two cents.) Commented Mar 6, 2012 at 23:00
  • @G That's a good question. I believe because I'm writing a simple console application that it's VB6 Commented Mar 6, 2012 at 23:12

3 Answers 3

3

By default, strWords will be Nothing by default anyway.

Rather than ensuring this value is never nothing by setting a value when declaring the variable, you should ensure your code doesn't leave the possibility of strWords being Nothing, and if it is, dealing with it appropriately.

If you need to check whether a string is not empty or nothing, you can do:

If Not String.IsNullOrEmpty(strWords) Then
Sign up to request clarification or add additional context in comments.

3 Comments

So if I write: If strWords Then.... will that check if strWords does not equal nothing?
@Scott - no. Use If Not String.IsNullOrEmpty(strWords) Then ...
+1 Although since this is VB, you can check whether the string is not empty or nothing like this If strWords <> "" Then The VB intrinsics treat Nothing as identical to ""
2

The best way to declare a string variable is to set it to an empty string directly after declaration. It is a common mistake for most .NET developers to set a string to "" or Nothing. This is wrong because "" is not really an empty string for .NET CLR, and Nothing could throw a NullReferenceException if you reference the string later in the code. Below is the correct code for string declaration:

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

1 Comment

A string set to Nothing is less likely to cause a NullReferenceException in VB than C#. The VB intrinsics treat Nothing as identical to ""
0

In .net and in VB.net, the best secure way to declare a string is give the variable a type name. For example:

Dim MyString As System.String

I like to declare a string (or any type) with fully qualified name to avoid confusion. And don't do this:

Dim MyString = "hello world"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.