Convert VB to C # conversion

I need help translating 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 a big problem, since IBase36 is double, Math.DivRem () in this case should return long and Long.Parse () to the right line.

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

Here is my translated working code thanks to 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;
    }
+3
source share
3 answers

To translate this, it is important to first understand how the VB.Net code works. Under the hood, it essentially generates the following

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

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

The most natural C # equivalent above:

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

:

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

- Is this what you want. Math.DivRem () returns the value that the above integer division must adhere to. The third out parameter returns the rest, but since you don't care about that in vb.NET code, you can just ignore it.

0
source

All Articles