Problems with Converting VB.NET Code to C#.NET

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jeepzhen
    New Member
    • Jan 2018
    • 5

    Problems with Converting VB.NET Code to C#.NET

    Hi experts, I'm Currently working on a project converting VB codes to C#. Now I'm facing a problem and not understand the VB Code to convert below codes into C# synthax.
    Please help to explain the below codes and provide me some hint on how to convert it.

    Code:
    Private Function Power2(ByVal exponent As Long) As Long
            Static result(0 To 31) As Long, i As Integer
             ' Evaluate all powers of 2 only once.
            If result(0) = 0 Then
                result(0) = 1
                For i = 1 To 30
                    result(i) = result(i - 1) * 2
                Next
                result(31) = &H80000000        ' This is a special value.
            End If
            Power2 = result(exponent)
    End Function
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    Notes:
    • you cannot have a static variable declared inside a method in C# so the static definition of the array of longs was moved outside of the method
    • &H80000000 is a hex number in VB.NET but in C# the hex notation is 0x80000000
    • this Power2 = result(exponent ) is an old school vb way of returning a value...therefo re the return keyword was used instead

    Code:
    static long[] result = new long[32];
    private long Power2(long exponent){
            // Evaluate all powers of 2 only once.
            if(result[0] == 0){
                result[0] = 1;
                for(int i = 1;i < 30; i++){
                    result[i] = result[i - 1] * 2;
                }
                result[31] = 0x80000000;       // This is a special value. (assuming its hex)
            }//end if
            return result[exponent];
    }//end of function
    I would recommend doing some validation before accessing the array index at the exponent... you will get an exception if you pass something larger than 31 or less than 0 as the exponent parameter...
    Last edited by Frinavale; Feb 28 '18, 10:14 PM.

    Comment

    Working...