Arrays in C#



Arrays  acts as a collection of objects, for example the wire you can use them to collect items in a group and perform various tasks on them, e.g. Sorting. Apart from this, many ways within the framework work on the array, which makes it possible to accept many items instead of only one. This fact alone makes it important to know something about Array

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];
The number (2) is the size of the array, that is, the amount of items we can put in it. Putting items into the array is pretty simple as well:
names[0] = "John Doe";
But why 0? As with the so many things in the world of programming, counting starts with 0 instead of 1. Therefore, the first item is indexed as 0, the next one and so on. When filling the array with items you should remember this, because filling it will create an exception. When you see the initiator, you set the array for the size of 2, then it may be natural to keep the item number 0, 1 and 2 in it, but this one item is too much. If you do this, an exception will be thrown. We will discuss the exceptions in a later chapter.

Before this, we have learned about loops, and obviously these are good with array. The most common way to get data from an array is to do some type of operation with loop and every value through it. Use the array in advance, to create a real 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();
        }
    }
}

for(int i = 0; i < names.Length; i++)
    Console.WriteLine("Item number " + i + ": " + names[i]);

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();
        }
    }
}







Share on Google Plus

About It E Research

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment