Velja Matic
Velja Matic

Reputation: 570

Translating VB to C# - type conversion

I need help with translating some code from VB to C#.

Public Function ToBase36(ByVal IBase36 As Double) As String
    Dim Base36() As String = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}
    Dim v As String
    Dim i As Decimal
    Do Until IBase36 < 1
        i = IBase36 Mod 36
        v = Base36(i) & v
        IBase36 = Math.DivRem(Long.Parse(IBase36), 36, Nothing)
    Loop
    Return v

End Function

My problem is how type conversion works in VB, and this line gives me most trouble since IBase36 is a double, Math.DivRem() in this case should return long and Long.Parse() need string.

IBase36 = Math.DivRem(Long.Parse(IBase36), 36, Nothing)

Here is my translated, working code thanks to the JaredPar and others

    public static string ToBase36(double IBase36)
    {
        string[] Base36 = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
        string v = null;
        long i = default(long);
        while (!(IBase36 < 1))
        {
            IBase36 = Convert.ToDouble(Math.DivRem(Convert.ToInt64(IBase36), 36, out i));
            v = Base36[i] + v;
        }
        return v;
    }

Upvotes: 3

Views: 290

Answers (3)

Erick Petrucelli
Erick Petrucelli

Reputation: 14872

Now try it:

long unused = null;
IBase36 = Convert.ToDouble(Math.DivRem(Convert.ToInt64(IBase36), 36, out unused));

Upvotes: 1

JaredPar
JaredPar

Reputation: 754575

To translate it's important to understand first how the VB.Net code functions. Under the hood it will essentially generate the following

Dim unused As Long
IBase36 = CDbl(Math.DivRem(Long.Parse(CStr(IBase36)), 36, unused)

Note: The unused variable is necessary because the third argument is an out. This is an important difference when translating to C#.

The most natural C# equivalent of the above is

long unused;
IBase36 = Convert.ToDouble(Math.DivRem(Long.Parse(IBase36.ToString()), 36, out unused);

Upvotes: 2

Bala R
Bala R

Reputation: 108937

IBase36  = (long)IBase36 / 36;

is what you want. Math.DivRem() returns the quotient which the above integer division should take care of. The third out parameter returns the remainder but since you don't care about it in vb. net code, you can just ignore that.

Upvotes: 0

Related Questions