Per Erik Strandberg /cv /kurser /blog

Arrays in C#

A code snippet that creates a minimal array in C#:

using System;

class MyArray
{
  static void Main(string[] args)
  {
    int[] myArray = new int[4];
    int i = 0;

    foreach (int a in myArray)
      Console.WriteLine("item {0} has value {1}", i++, a);
  }
}

Compile it and the not so sexy output is:

 item 0 has value 0
 item 1 has value 0
 item 2 has value 0
 item 3 has value 0

Visual Basic .NET

The corresponding example in Visual Basic should be something like this:

Module myVisualBasicArray

  Sub Main()
    Dim myArr(4) As Integer
    Dim i As Integer = 0

    Do While (i < myArr.Length)
      Console.WriteLine("item in position {0} is {1}", i, myArr(i))
      i += 1
    Loop

  End Sub

End Module

The output is similar, but not identical

item in position 0 is 0
item in position 1 is 0
item in position 2 is 0
item in position 3 is 0
item in position 4 is 0

Conclusion

Allocating arrays in Visual Basic is done with the number of the largest index one wants to access, not the number of elements in the array.

Links


This page belongs in Kategori Programmering.