Bill
Bill

Reputation: 23

Convert C# format to VB

I am sure this is a simple question for you guys but I don't know what this developer is doing.

name = String.Format(MyStringBuilder + "");

If I convert this to VB I get the message "operator + is not defined for types system.text.stringbuilder and string". Same thing if I use &.

Upvotes: 1

Views: 356

Answers (6)

Andrew Lewis
Andrew Lewis

Reputation: 5256

In VB.NET you would use a "&" instead of a "+"

This line:

name = String.Format(MyStringBuilder + "");

Is causing an implicit cast of MyStringBuilder to string (using the ToString() method) in order to use the "+" operator. It's the same as:

name = String.Format(MyStringBuilder.ToString() + "");

which is the same as

name = MyStringBuilder.ToString();

which becomes this in VB.NET:

name = MyStringBuilder.ToString()

Upvotes: 0

Anthony Pegram
Anthony Pegram

Reputation: 126794

In the strictest sense, MyStringBuilder in the original code could be a null instance, at which point making an explicit call to .ToString() would throw an exception. The code sample provided would execute properly, however. In VB, you may want to say

Dim name As String
If MyStringBuilder Is Nothing Then
   name = String.Empty
Else
   name = MyStringBuilder.ToString()
End If

Upvotes: 5

anonymous
anonymous

Reputation: 3544

You're trying to concatenate a StringBuilder object and String together - that wouldn't work :)

name = String.Format(MyStringBuilder.ToString() + "");

This should compile correctly.

Upvotes: 0

Tom Cabanski
Tom Cabanski

Reputation: 8018

Use MyStringBuilder.ToString(). That will fix the problem.

Upvotes: 1

Joel Etherton
Joel Etherton

Reputation: 37523

It looks as if the person who wrote it is attempting to force an implicit conversion of MyStringBuilder to a string using the + operator in conjuction with the empty string.

To perform this assignment in VB you only need:

name = MyStringBuilder.ToString()

Upvotes: 11

Broam
Broam

Reputation: 4648

That doesn't make sense to me because AFAICT passing only one argument to string.format doesn't do anything.

Adding "" to the stringbuilder just coerces it to a string.

name = MyStringBuilder.ToString(); would be how I'd do this in C#. Converting that statement to VB should be loads easier.

Upvotes: 2

Related Questions