PDA

Click to See Complete Forum and Search --> : {RESOLVED} Declaring Array in C#...


Wen Lie
Jul 20th, 2007, 07:22 AM
Hello...

I'm confusing on how to declare array variable in C#...
In VB, I used as below :

Dim myArray(10) as String
Dim iL as Byte

for iL = 0 to 9
myArray(iL) = iL
next iL


how should I do the above code in C# ?

Regards,
~WJ~

Paul M
Jul 20th, 2007, 07:37 AM
String[] myArray = new String[10];


that would be how you declare the array :)

Wen Lie
Jul 20th, 2007, 07:42 AM
thanks.
and to set the value ?


myArray[0] = "Test";


Regards,
~WJ~

Paul M
Jul 20th, 2007, 07:44 AM
Yes correct :)

jmcilhinney
Jul 20th, 2007, 07:48 AM
Firstly, you should understand the difference between declaring a variable and creating an object. You are doing both in that code, but neither requires the other. This is a variable declaration:Dim myArray As String()That creates a variable on the stack that can contain the memory address of a string array, but no array object is created on the heap. This is the same:Dim myArray() As String()Whenever you specify a length for an array, either explicitly or implicitly, you are creating an object. These all do that:Dim myArray1(10) As String
Dim myArray2() As String = New String(10) {}
Dim myArray3() As String = New String() {}
Dim myArray4() As String = New String() {"string1", "string2"}You should also note that the code you posted is creating an array with 11 elements and then setting only 10 of them. In VB you specify the upper bound, not the length. If you want an array with 10 elements then you should specify 9 when creating the array. You're also assigning Bytes to the elements of a String array. The more appropriate code would be:Dim length As Integer = 10
Dim upperBound As Integer = length - 1
Dim myArray(upperBound) As Byte

For b As Byte = 0 To upperBound Step 1
myArray(b) = b
Next bIn C# the equivalent would be:int length = 10;
byte myArray[] = new byte[length];

for (byte b = 0; b < length; b++)
{
myArray[b] = b;
}Note that in C# you DO specify the length when creating an array.

Wen Lie
Jul 20th, 2007, 09:29 AM
yup.
it works.
thanks for alll of your help.

Regards,
~WJ~