ideas | discover | explore

Thursday, October 13, 2011

C# 11 - Arrays

An array of sorts.

1. Create a new console project.
2. Edit the Program.cs inside static void Main(string[] args) file as shown below.
static void Main(string[] args)
{
     //declaring and initializing an array
     string[] theAvengers = new string[5];
     theAvengers[0] = "Iron Man";
     theAvengers[1] = "Thor";
     theAvengers[2] = "Captain America";
     theAvengers[3] = "Hawkeye";
     theAvengers[4] = "Hulk";
 
     Console.WriteLine("The Avengers!");
     Console.WriteLine("-------------------------");
     //loop through an array to access or modify its contents
     for (int i = 0; i < 5; i++)
     {
         Console.WriteLine(theAvengers[i]);
     }
 
     //another way of declaring and initializing an array
     //also another way is
    //string[] uncannyXMen = new string[] { "Wolverine", "Prof. X", "Cyclops", "Storm", "Beast" };
     string[] uncannyXMen = { "Wolverine""Prof. X""Cyclops""Storm""Beast" };
             
     Console.WriteLine("\nThe X-Men!");
     Console.WriteLine("-------------------------");
     //loop through an array to access in contents
     for (int i = 0; i < uncannyXMen.Length; i++)
     {
          Console.WriteLine(uncannyXMen[i]);
     }
 
     Console.WriteLine("Press any key to continue...");
     Console.ReadLine();
}

3. Press F5 to run and see the results.

4. Thank you.

Declaring an array allows you to store multiple items of a specific type. It syntax is:

type[] arrayName;

To learn more about arrays check these resources.

No comments: