Strings, a couple of questions like difference between += and &=

  • Thread starter Thread starter James
  • Start date Start date
J

James

What's the difference between += and &= with reference to strings?

Also, what are string literals? Thanks.

And what are fixed lenth strings? and how do you declare them? Thanks
 
James,

It is better not to use in visual basic the + with strings. There can be
problems with that when you have option strict of.

string b as string = 10
b += "2"
will result in 12 with option strict of.

string b as string = 10
b &= "2"
will result in 102, mostly the wanted result in this kind of use.

I hope this gives an idea,

Cor
 
Cor Ligthert said:
It is better not to use in visual basic the + with strings. There can be
problems with that when you have option strict of.

That's true. In addition you need 'CStr' or 'ToString' calls which are not
always necessary when using '&' because it performs conversion to string
automatically.
string b as string = 10
b += "2"
will result in 12 with option strict of.

No, it will result in "102".
 
James said:
What's the difference between += and &= with reference to strings?

With Option Strict On - which I would /strongly/ recommend -
None at all.

With Option Strict Off, the + sign can be "misinterpreted" by the
compiler depending on the Type of data values being used.

Dim s As String = "3"
Dim i As Integer = 1

s += i

Should the result be "31" ("3" + CStr(1)) or "4" (CStr(CInt("3") + 1)))?

Stick to "&" - there's no confusion that way.
And turn Option Strict On so you can't trip yourself up.
Also, what are string literals?

"This is a String Literal" :-)

String Literal ::= A string value that appears /in your code/ with
leading and trailing double-quotes.
And what are fixed lenth strings? and how do you declare them? Thanks

These are Strings whose value is /always/ a pre-defined number of
characters long, no matter how much you try to put into it.
For example, if you have a five-character fixed-length String, fs:

fs = "A"
?"(" & fs & ")"
(A )

They're useful if you're dealing with flat (say, COBOL-generated) files
where each data field is delimited /only/ by its total length.

Avoid using them if at all possible. Instead, write code that reads and
writes the fixed-length data, but store the values internally in
ordinary, variable-length Strings.

HTH,
Phill W.
 
Back
Top