422,754 Members | 2,297 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 422,754 IT Pros & Developers. It's quick & easy.

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

P: 5
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.

Expand|Select|Wrap|Line Numbers
  1. Private Function Power2(ByVal exponent As Long) As Long
  2.         Static result(0 To 31) As Long, i As Integer
  3.          ' Evaluate all powers of 2 only once.
  4.         If result(0) = 0 Then
  5.             result(0) = 1
  6.             For i = 1 To 30
  7.                 result(i) = result(i - 1) * 2
  8.             Next
  9.             result(31) = &H80000000        ' This is a special value.
  10.         End If
  11.         Power2 = result(exponent)
  12. End Function
  13.  
Feb 26 '18 #1
Share this Question
Share on Google+
1 Reply


Frinavale
Expert Mod 5K+
P: 9,731
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...therefore the return keyword was used instead
Expand|Select|Wrap|Line Numbers
  1. static long[] result = new long[32];
  2. private long Power2(long exponent){
  3.         // Evaluate all powers of 2 only once.
  4.         if(result[0] == 0){
  5.             result[0] = 1;
  6.             for(int i = 1;i < 30; i++){
  7.                 result[i] = result[i - 1] * 2;
  8.             }
  9.             result[31] = 0x80000000;       // This is a special value. (assuming its hex)
  10.         }//end if
  11.         return result[exponent];
  12. }//end of function
  13.  
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...
Feb 28 '18 #2

Post your reply

Sign in to post your reply or Sign up for a free account.