Search This Blog

Friday, 20 July 2012

Arrays


Arrays works as collections of items, for instance strings. You can use 
them to gather items in a single group, and perform various operations 
on them, e.g. sorting. Besides that, several methods within the 
framework work on arrays, to make it possible to accept a range of items
instead of just one. This fact alone makes it important to know a bit 
about arrays. 

Arrays are declared much like variables, with a set of [] brackets after the datatype, like this:

string[] names;

You need to instantiate the array to use it, which is done like this:

string[] names = new string[2]; 
   

Example:

 

using System;
using System.Collections;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] names = new string[2];
 
            names[0] = "John Doe";
            names[1] = "Jane Doe";
 
            foreach(string s in names)
                Console.WriteLine(s);
 
            Console.ReadLine();
        }
    }
}

Let's try sorting the array - here's a complete example:

using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = { 4, 3, 8, 0, 5 };

            Array.Sort(numbers);

            foreach(int i in numbers)
                Console.WriteLine(i);

            Console.ReadLine();
        }
    }
}


Next Chapter

No comments:

Post a Comment