开发者

Convert C# format to VB

I am sure this is a simple question for you guys but I don't know what th开发者_开发百科is 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 &.


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()


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


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.


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


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

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

This should compile correctly.


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()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜