|
-
Jul 20th, 2007, 07:22 AM
#1
Thread Starter
Fanatic Member
{RESOLVED} Declaring Array in C#...
Hello...
I'm confusing on how to declare array variable in C#...
In VB, I used as below :
Code:
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~
Last edited by Wen Lie; Jul 20th, 2007 at 09:30 AM.
Reason: Resolved....
-
Jul 20th, 2007, 07:37 AM
#2
Re: Declaring Array in C#...
vb Code:
String[] myArray = new String[10];
that would be how you declare the array
-
Jul 20th, 2007, 07:42 AM
#3
Thread Starter
Fanatic Member
Re: Declaring Array in C#...
thanks.
and to set the value ?
Code:
myArray[0] = "Test";
Regards,
~WJ~
-
Jul 20th, 2007, 07:44 AM
#4
Re: Declaring Array in C#...
Yes correct
-
Jul 20th, 2007, 07:48 AM
#5
Re: Declaring Array in C#...
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: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:
vb.net Code:
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:
vb.net Code:
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:
vb.net Code:
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 b
In C# the equivalent would be:
Code:
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.
-
Jul 20th, 2007, 09:29 AM
#6
Thread Starter
Fanatic Member
Re: Declaring Array in C#...
yup.
it works.
thanks for alll of your help.
Regards,
~WJ~
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|