Question need help to convert vb.net coding to c#

tiwana22

New member
Joined
Aug 31, 2018
Messages
4
Programming Experience
Beginner
hi guys, im new to this forum and beginner to c# too

i had a code to generate key in vb.net, bt for sm reasons i switched to c# and need to convert vb.net coding to c#
I converted it online, bt it doesnt work for me : Please have a look on coding

C#:
Public Function GenCode(ByVal strUN As String) As String

        Dim P1 As Long, P2 As Long, P3 As Long
        Dim S1 As String, S2 As String, S3 As String
        Dim j As Integer

        For j = 1 To Len(strUN)
            P1 = P1 + Asc(Mid(strUN, j, 1)) * 15
        Next
        strUN = LCase(strUN)
        For j = 1 To Len(strUN)
            P2 = P2 + Asc(Mid(strUN, j, 1)) * 20
        Next
        strUN = UCase(strUN)
        For j = 1 To Len(strUN)
            P3 = P3 + Asc(Mid(strUN, j, 1)) * 25
        Next

        S1 = CStr(Hex(P1))
        S2 = CStr(Hex(P2))
        S3 = CStr(Hex(P3))

        If Len(S1) > 4 Then S1 = Left(S1, 4)
        If Len(S2) > 4 Then S2 = Left(S2, 4)
        If Len(S3) > 4 Then S3 = Left(S3, 4)

        GenCode = S1 & "-" & S2 & "-" & S3
    End Function

I think the problem is of ASC and HEX, which c# does not recognize. Hope i will get its solution here.

Regards and Thanks in advance :)
 
You are correct that Asc and Hex are VB-specific. The thing to do is to learn what they do, then learn how to do that in a non-VB-specific way, then modify the VB code accordingly, then convert the result to C#. You shouldn't really be blindly converting code without understanding what it actually does so that should be your first step. You'll find similar issues with Len, LCase, UCase and Left.

To be honest, I suspect that that is VB6 code, or was originally anyway. There's nothing really .NET-specific there and there's a lot that looks like it was written by someone more familiar with VB6 than .NET. The good news is that there are .NET-specific ways to do all that stuff so you can easily write good VB.NET code to achieve your aim, then you can convert that to C# code with very little trouble.

For future reference, online converters can do a decent job of simple code but most of them falter when they come up against new language features. I would suggest that you download Instant C# and possibly Instant VB as well from Tangible Software Solutions. The free versions are quite enough for most people and they are close to 100% accurate regardless of the code complexity. Instant C# might even automatically handle VB-specific functions like Asc and Hex.
 
Could you provide a couple sample inputs and what the outputs are?

Untitled.jpg

Please have a look.
 

Attachments

  • Untitled.jpg
    Untitled.jpg
    8.5 KB · Views: 75
Back
Top Bottom