Tech Junkie Blog: C# : Arrays

Thursday, February 19, 2015

C# : Arrays

Arrays are fixed size elements of a type, arrays are stored next to each other in the memory. Making them very fast and efficient.  However you must know the exact size of an array when you declare an array.

Declaring an array:
string[] names = new string[5];
There are two ways you can assign values to an array. The first is to assign the values individually by specify the index of the array inside a square bracket. The index is the position of element in the array. Index starts with 0.
names[0] = "George";
names[1] = "James";
names[2] = "Arthur";
names[3] = "Eric";
names[4] = "Jennifer";
Or you can initialize and populate the array at the same time, like the example below.
string[] names = new string[]{"George","James","Arthur","Eric","Jennifer"};
You don't have to specify the size of the array if you initialize during the declaration, C# is smart enough to figure out the array size from the initialization. You can loop through an array with a foreach loop
  foreach(string n in names)
  {
     Response.Write(n + "");
  }
Or a for loop
 for(int i=0; i < names.Length;i++)
{
    Response.Write(n + "");
 }

No comments:

Post a Comment