Using Strings in C# converted from VB

Status
Not open for further replies.

J Trahair

Well-known member
Joined
May 14, 2008
Messages
175
Location
Spain
Programming Experience
10+
Hi all

I have converted some VB into C#, but the VB functions Format, Mid, Asc, Chr, Replace, Trim, Len and Val produce the error:
HTML:
Error 1 The name 'Strings' does not exist in the current context etc.

The conversion site produced the following code (edited by me):
HTML:
Strings.Format(gnumValueToWrite, "000")
Strings.Mid(strUnoffsetTextStringToWrite, 1, 1)
Strings.Asc("d")
Strings.Chr(69)
Strings.Replace(strBufferAll, "a", "b")
Strings.Trim("Tomorrow   ")
Strings.Len(strStringAsHex)
Conversion.Val("12")

In C#, how do you do the functions above (as examples)?

Thanks in advance.

Jonathan
 
String class has equivalents for most of those VB runtime functions (in Microsoft.VisualBasic.dll). For Asc/Chr there is Convert.ToInt32/ToChar methods.

Also this is a VB.Net forum, you know what that means, right? C# Developer Forums
 
If that was good VB.NET code in the first place instead of basically VB6 code then there would be no issue.
Strings.Format(gnumValueToWrite, "000") 'Should be using String.Format
Strings.Mid(strUnoffsetTextStringToWrite, 1, 1) 'Should be using String.Substring
Strings.Asc("d") 'Should be using Convert.ToInt32
Strings.Chr(69) 'Should be using Convert.ToChar
Strings.Replace(strBufferAll, "a", "b") 'Should be using String.Replace
Strings.Trim("Tomorrow   ") 'Should be using String.Trim
Strings.Len(strStringAsHex) 'Should be using String.Length
Conversion.Val("12") 'Should probably be using Double.TryParse
I'd suggest rewriting the VB code well first and then converting it to C# will be a matter adding semicolons.
 
It seems that
HTML:
Strings.Asc("d") 'Should be using Convert.ToInt32
only converts "d" to an Int32, not to the ASCII value for "d". This causes an error.

The correct working code is
VB.NET:
            strInput = "x";
            numResult = (int)strInput[0];
            MessageBox.Show("numResult = " + numResult);
which will show 120, the correct answer.

Thank you.
 
I'd suggest rewriting the VB code well first and then converting it to C# will be a matter adding semicolons.
That is a good suggestion, I have the same experience when porting VB.Net to C# using code converter.
It seems that
HTML:
Strings.Asc("d") 'Should be using Convert.ToInt32
only converts "d" to an Int32, not to the ASCII value for "d". This causes an error.
For this use Convert.ToInt32 accepts a Char value, not a String value. Convert the single char String value to Char data type first:
Dim asc = Convert.ToInt32(CChar("d"))

Ascii value for "d" character is 100, which is the result.

Convert.ToInt32(String) is for convert string representations of a number (like Parse), such as the string "123".
 
Status
Not open for further replies.
Back
Top