Click here to Skip to main content
15,889,610 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
I have code as follow:

Dim aRead() As String
      Dim  nCnt,i As Iteger  
      nCnt = 0
      For i=0 to 5               
         ReDim Preserve aRead(nCnt)                           
         aRead(nCnt) = i
      Next i
      nCnt = nCnt + 1


and now I want to convert it to C#, so How must I do?
I tried as below but not:
int i,nCnt = 0;
string[] aRead = null;
For(i=0;i<=5;i++){
Array.Resize(ref aRead, nCnt);
aRead[nCnt] = i;
nCnt = nCnt + 1;
}


could you help me please.
thanks.
Posted
Updated 17-Feb-11 14:34pm
v3

The closest C# equivalent is Array.Resize<T> but even that creates a new array and copies over the old array into the new array.

If you want an array-like collection that can grow as required, use List<T>. That would be a more .NET-ish way of doing things.

When moving from classic VB to .NET, it's not enough to learn the new syntax, you also need to understand the new framework and try and follow recommended .NET practices.
 
Share this answer
 
v4
Comments
Henry Minute 17-Feb-11 20:32pm    
Good answer.
Nish Nishant 17-Feb-11 20:34pm    
Thanks Henry!
Sergey Alexandrovich Kryukov 17-Feb-11 20:33pm    
All correct, my 5.
--SA
Nish Nishant 17-Feb-11 20:34pm    
Thanks SA.
fjdiewornncalwe 17-Feb-11 22:59pm    
Agreed! +5
As Nishant mentioned Array.Resize will do it. But it is expensive operation as each call will create a new array.

Alternatively, you know from your code above your array size ahead of time. So you don't need to Resize it in the loop, rather have it defined once and you are done.

C#
int i;
string[] aRead = new string[5];
for(i=0;i<=5;i++){
 aRead[i] = i;
}


Alternative 2: If you think you will need to grow your array then use ArrayList[^]

ArrayList myAL = new ArrayList();
for(i=0;i<=5;i++){
      myAL.Add(i);
}
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 17-Feb-11 22:22pm    
That is a good note, my 5.
We probably assumed that if OP asked for Resize, it is really required, but you analyzed the problem and found that not only Resize, but even a list is not needed, so your code is the fastest.
--SA
Yusuf 18-Feb-11 8:25am    
Thanks SA
I use for from 0 to 5 to for example and the problem in here is I can not riseze array in loop.Because when I debug it the first run it is resized ok but the second has bug.
I think that in C# it do not allow we risize array in loop as in VB. Maybe I must count the time loop and then resize my array and this way is ok.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900