c# – Arrays

Arrays are used to store a a group of items as a collection:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Arrays
{
    class Program
    {
        static void Main(string[] args)
        {
            // Here we are creating an array called "vowels", that can house up to 5 items. 
            string[] vowels = new string[5];
            vowels[0] = "a";
            vowels[1] = "e";
            vowels[2] = "i";
            vowels[3] = "o";
            vowels[4] = "u";
			
            for (int i = 0; i < vowels.Length; i++)
			{
				Console.WriteLine(vowels[i]);
			}

			// Here is another way to declare an array, where you set all the values in a single line:
			string[] fruits = {"apple","bananas","oranges","mangoes"};
	
			for (int i = 0; i < fruits.Length; i++)
			{
				Console.WriteLine(fruits[i]);
			}

			// Here is an array of integers:
			int[] PrimaryNumbers = {1,2,3,5,7,11,13};
	
			for (int i = 0; i < PrimaryNumbers.Length; i++)
			{
				Console.WriteLine(PrimaryNumbers[i]);
			}
			
			
			// The following only outputs "System.String[]" or "System.Int32[]", hence not that useful. 
			Console.WriteLine(vowels);
			Console.WriteLine(fruits);
			Console.WriteLine(PrimaryNumbers);
		}
    }
}

Tip: In the above examples we used the for-loop to process each item in the variable. However, it is often easier to use the foreach loop instead (we will do this in our next example).

Arrays can also be used to store custom variable objects:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Arrays
{
    class Program
    {
        static void Main(string[] args)
        {

            Employee[] Employees = new Employee[3];
            Employees[0] = new Employee("David");
            Employees[1] = new Employee("Jennifer");
            Employees[2] = new Employee("Jonathon");
			
			// We used the for loop above, however when 
			// working with arrays it is often easier 
			// to output using the foreach loop instead:
			foreach (Employee item in Employees)
			{
				Console.WriteLine(item.Name);
			}

		}
    }
	
	class Employee
    {
        public string Name {get; set;}
 
        public Employee (string Name)
        {
            this.Name = Name;
        }
    }
	
}

For more info about arrays, checkout:

http://msdn.microsoft.com/en-us/library/system.array.aspx

http://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx

However arrays have one big limitation, and that is that you can’t add extra items to an array that is already contains the maximum number of items.