Makai Studio
Imi ‘Ike - Seeker Of Knowledge
Imi-?ike

Using Arrays - C# Tutorial and Sample - Part 1

February 8, 2008 19:20 by jdelpay

An Array is an unordered sequence of elements. All the elements in an array have the same type, followed by a pair of square brackets, followed by the variable name.
   

int[] pinNumbers; //personal identification numbers


note: C and C++ programmers should note that the size of the array is not part of thedeclaration.


Arrays are reference type
The size of an array does not have to be a constant, it can be calculated at run time.

int size = int.Parse(Console.ReadLine());
    int[] pinNumbers = new int[size];


Its possible to create arrays of size 0. Useful in situations where the size is determined dynamically. Array with size 0 is not a null array.


Initializing Array Variable
i.e Initializing pinNumbers to an array of 4 int with the following values: 9,3,7,2

 

int[] pinNumber = new int[4] {9,3,7,2};

// the number in the curly bracket must match the size of the array


the value within the curly brace do not have to be constants.
   

Random r = new Random();

int[] pinNumber = new int[4]{ r.next() %10, r.next() %10,

r.next() %10, r.next() %10};


note: The system.Random class is a pseudo -random number generator. The Next method returns a nonnegative random number.


When initializing an array, you can omit the 'new' expression and the size of the array:

int[] pinNumbers {9,7,3,2};

   
Accessing Individual Array Elements

  To access an individual array element you must provide an index indicating which element you require.

int myNumber; 
 
    myNumber =  pinnumbers[3] ; 
 

you can also change the contents of an array by assigning a value to an indexed element:

myNumber = 167; 
 
pinnumbers[2] = myNumber; 
 

the initial element in an array is indexed 0 (zero) and not 1.

All array elements access is bounds-checked. when using an integer index that is less than 0 or greater than or equal to the lengh of the array, the compiler throws an indexOutOfRangeException

try 
 
    { 
 
        int[] pinnumbers ={9,3,7,2}; 
 
         Console.WritLine(pinNumber[4]); //error, the 4th element is at index 3 
 
   } 
 
   catch(indexOutOfRangeException ex) 
 
   { 
 
      ... 
 
   }

Visit:Makai Studio

AddThis Social Bookmark Button

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: ASP.Net | C#
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

Related posts

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

May 16. 2008 16:16