When you declare an array, you don’t have to specify the capacity of the array.
You have to do this while initializing arrays.
[VB] Dim v as Integer()
[CS] int[] v;
This is just declaration of integer array variable. Value of v is nothing/null.
Initializing arrays with 5 elements
[VB] v = new Integer(4){}
[CS] v = new int[5]
in Visual Basic, the value specified within the parenthesis are Upper bound and the lower bound is always zero. Hence it can hold 5 elements (0,1,2,3,4).
VB developers: To avoid confusion, you can declare like this
[VB] v = new Integer(0 to 4){}
Array elements can be accessed with indexes
[VB] Dim n as Integer = v(2)
[CS] int n = v[2]
Index can also be variable
[VB]
Dim index as integer = 2
Dim n as Integer = v[index]
[CS]
int index = 2;
int n = v[index];
Accessing array elements by indexes gives a great opportunity for working with large set of data.
You can access series of elements using looping constructs.
[VB]
For index as Integer = 0 to 4
v(index) = index * 10
Console.WriteLine(v(index))
Next
[CS]
for(int index=0;index<5;index++)
{
v[index] = index * 10;
Console.WriteLine(v[index]);
}
Also you can access elements with foreach loops
[VB]
Foreach element as Integer in v
Console.WriteLine(element)
Next
[CS]
foreach(int element in v)
{
Console.WriteLine(v[element])
}
No comments:
Post a Comment