You are on page 1of 41

Arrays in C#

Prepared By:
Esha Batish
Lecture No-25
Date-26-04-2011
Introduction to Arrays
• An array is a collection of variables of the
same type that are referred to by a common
name.
• The principal advantage of an array is that it
organizes data in such a way that it can be
easily manipulated.
• Arrays can be One dimensional, Two
Dimensional or Multi-Dimensional.
• Commonly used are One dimensional, Two
Dimensional. Contd..
• Although arrays in C# can be used just like
arrays in many other programming languages,
they have one special attribute: They are
implemented as objects. By implementing
arrays as objects, several important advantages
are gained, such as they are automatically
garbage-collected.
• In C#, arrays can be declared as fixed length
or dynamic.
• The array name behave as constant pointer
which hold the reference of first element of
array. Contd..
• Arrays are represented using Dimensions i.e.[]
Such as : DataType[] ArrayName;
DataType describe the type of elements array
is going to store in it.
• In Memory, Array is used to store in
sequential manner. (Fig.1 Arrays in Memory)
Array Name

Base Address Index Element


Array Declaration & Intialization
• An array is declared by defining the type of
elements inside the array followed by empty
brackets and a variable name in c#. Such as:
• For e.g. int[] myArray;
• This myArray is going to store integral value
and name of the array will hold the base
address of the array elements.
• Memory must be allocated to hold all the
elements of the array. An array is a reference
type, so memory on the heap must be allocated.
Contd..
• The process of allocation of memory to
declared array is called Array Initialization.
• Initialization is done with new keyword such
as
myArray=new int[4];
• The Declaration and initialization can be done
in single line also:
int[] myArray=new int[4];
• This statement will force compiler to instruct
Operating System to allocation memory for 4
elements; each having 4bytes to store. Contd..
Memory Representation
• Name of the array is value type but it is
allocated memory using new keyword so
memory allocated is on Heap.(Fig2.Memory
for myArray). It’s a Single-Dimension Array.
• You can also assign values to every array
element using an array initializer. Array
initializers can be used only while declaring
an array variable, not after the array is
declared:
• int[] myArray = new int[] {4, 7, 11, 2};
• In this case there is no need to specify the size
as size is evaluated with number of elements
passed in {}.
• Using curly brackets you can write the array
declaration and initialization. Contd..
• int[] myArray = {4, 7, 11, 2};
• Accessing Array Elements: Elements of an
array is accessed using index element in
dimensions.
• int[] myArray = new int[] {4, 7, 11, 2};
• int v1 = myArray[0]; // read first element
• int v2 = myArray[1]; // read second element
• myArray[3] = 44; // change fourth element

Contd..
• If you use a wrong indexer value where no
element exists, an exception of type
IndexOutOfRangeException is thrown.
• If you don ’ t know the number of elements in
the array, you can use the Length property
that is used in this for statement:
• for (int i = 0; i < myArray.Length; i++)
• {
• Console.WriteLine(myArray[i]);
• } Contd..
• Instead of using a for statement to iterate
through all elements of the array, you can
also use the foreach statement:
• foreach (int val in myArray)
• {
• Console.WriteLine(val);
• }
Using Reference Types
• In stead of declaring arrays of predefined
types, you can also declare arrays of custom
types. Lets Person is a user defined class, we
can create array of this class such as:
• Person[] Per = new Person[2];
• This array will hold memory for the data of
objects of Person class.
• If elements of an array is of reference type
then memory should be allocated, otherwise
NullReferenceException is thrown. Contd..
• You can allocate every element of the array by
using an indexer starting from 0:
• Per[0] = new Per ();
• Per[1] = new Per(); e.g.
class Program
{
static void Main(string[] args)
{
person[] myPerson = new person[2];
myPerson[0] = new person(3);
myPerson[1] = new person(4); Contd..
myPerson[0].dis();
myPerson[1].dis();
Console.ReadKey();
}
}
class person
{
int x;
public person(int x)
{
this.x = x;
} Contd..
public void dis()
{
Console.WriteLine(x);
}
}

Output:
3
4
Memory Representation
Multi-Dimensional Array
• Ordinary arrays (also known as one -
dimensional arrays) are indexed by a single
integer. A multidimensional array is indexed
by two or more integers. Array with 2
dimension usually represent rows and
columns.
• A is a 2d array.
• Declaring this two - dimensional array with
C# is done by putting a comma inside the
brackets. The array is initialized by specifying
the size of every dimension (also known as
rank). Then the array elements can be
accessed by using two integers with the
indexer:
• int[,] a= new int[3, 3];
• Here 2D array contains 3 rows and 3
columns.
• Values can be initialize as: Contd..
a[0,0]=2;
a[2,3]=9;
• Another way to initialize 2D array is:
• int[,] a = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
• When using an array initializer, you must initialize
every element of the array. It is not possible to leave
the initialization of some values for later.
Three-Dimensional Array
• By using two commas inside the brackets, you
can declare a three - dimensional array:
• int[,,] threedim = {
{ { 1, 2 }, { 3, 4 } },
{ { 5, 6 }, { 7, 8 } },
{ { 9, 10 }, { 11, 12 } }
};
• Console.WriteLine(threedim[0, 1, 1]);
Contd..
Jagged Arrays
• A jagged array is more flexible in sizing the
array. With a jagged array every row can
have a different size.
• Each row of jagged array can have different
number of elements. Let’s compare with 2D
arrays.
• A jagged array is declared by placing one pair of
opening and closing brackets after another. With the
initialization of the jagged array, only the size that
defines the number of rows in the first pair of
brackets is set. The second brackets that define the
number of elements inside the row are kept empty
because every row has a different number of
elements. Next, the element number of the rows can
be set for every row:
• int[][] jagged = new int[3][];
• jagged[0] = new int[2] { 1, 2 };
• jagged[1] = new int[6] { 3, 4, 5, 6, 7, 8 };
• jagged[2] = new int[3] { 9, 10, 11 };
• Iterating through all elements of a jagged array
can be done with nested for loops. In the outer for
loop every row is iterated, and the inner for loop
iterates through every element inside a row.
• for (int row = 0; row < jagged.Length; row++)
{
for (int element = 0; element <
jagged[row].Length; element++)
{
Console.WriteLine(jagged[row][element]);
}
}
Question for you…
• Write a program to display a table which
should be look like as the following one:
Solution is…
class jagged_array
{
public static void Main(string []args)
{
int[][] jagged = new int[3][];
jagged[0] = new int[2];
jagged[1] = new int[6];
jagged[2] = new int[4];
int i=0; Contd..
for (int j = 0; j < jagged[0].Length; j++)
jagged[i][j] = 1;
i++;
for (int j = 0; j < jagged[1].Length; j++)
jagged[i][j] = 2;
i++;
for (int j = 0; j < jagged[2].Length; j++)
jagged[i][j] = 3;
i++; Contd..
for (int k=0, j = 0; j < jagged[0].Length; j++)
Console.Write(" "+jagged [k][j]);
Console.WriteLine();
for (int k=0, j = 0; j < jagged[1].Length; j++)
Console.Write(" "+jagged [k][j]);
Console.WriteLine();
for (int k=0, j = 0; j < jagged[2].Length; j++)
Console.Write(" "+jagged [k][j]);
Console.WriteLine();
Contd..
Console.ReadKey();
}
}
Jagged arrays some how important where we
need to store variation of data such as every
person has different number of hobbies.
Array Class
• There is a predefined class “Array” in csharp.
• The Array class is abstract, so you cannot
create an array by using a constructor.
• So it is possible to create arrays by using the
static CreateInstance() method.
• This is extremely useful if you don’t know the
type of elements in advance, because the type
can be passed to the CreateInstance() method
as a Type object. Contd..
Array A = Array.CreateInstance(typeof(int), 5);
for (int i = 0; i < 5; i++)
{
A.SetValue(33, i);
}
• The first argument of the CreateInstance()
method requires the type of the elements, and
the second argument defines the size.You can
set values with the SetValue() method and
read values with the GetValue() method.
for (int i = 0; i < 5; i++)
{
Console.WriteLine(A.GetValue(i));
}
• You can also cast the created array to an
array by declaring it as int[]:
• int[] intArray2 = (int[])A;
Quiz for you…

1.Which one of the following is not advantage


of array
• Storing list of data
• Static Data Structure
• Sequential Memory Access
• All of them
Ans : Static Data Structure
2.Array name is an constant pointer because

• It hold reference of array


• Its value can’t be changed
• It hold Reference of Base element
• All of them
Ans: It hold Reference of Base element
3.CreateInstance() is defined in class
• Type
• Math
• Array
• ArrayList
Ans: Array
4.What will be the output of following code:
• class Class3
• {
• public static void Main(string []args)
• {
• int[] myArray = new int[5];
• for (int i = 0; i <= myArray.Length; i++)
• {
• Console.WriteLine(myArray[i]);
• }
• }
• }
•  
Copying Arrays
• Because arrays are reference types, assigning
an array variable to another one just gives
you two variables referencing the same array.
• For copying arrays, the array implements the
interface ICloneable. The Clone() method that
is defined with this interface creates a copy of
the array.
• For e.g. int[] intArray1 = {1, 2};
• int[] intArray2 = (int[])intArray1.Clone();
Contd..
Instead of using the Clone() method, you can use the
Array.Copy() method, which creates a copy as well. But there
’ s one important difference. Clone() creates a new array;
with Copy() you have to pass an existing array with the same
rank and enough elements.
Sorting
• The Array class uses the QuickSort algorithm
for sorting the elements in the array. The
Sort() method requires the interface
IComparable to be implemented by the
elements in the array. Simple types such as
System.String and System.Int32 implement
IComparable , so you can sort elements
containing these types.
Such as:
Contd..
• string[] names = {"Christina ",
"Shakira","Beyonce","Gwen Stefani"};
Array.Sort(names);
foreach (var name in names)
{
Console.WriteLine(name);
}
Output:
• Beyonce
• Christina
• Gwen Stefani
• Shakira
Arrays can be passed as parameters to methods, and
returned from methods. Returning an array, you just
have to declare the array as the return type, as shown
with the following method GetPersons() :
• static Person[] GetPersons()
• {
• return new Person[] {
• new Person { FirstName="Damon", LastName="Hill" },
• new Person { FirstName="Niki", LastName="Lauda" },
• new Person { FirstName="Ayrton", LastName="Senna" },
• new Person { FirstName="Graham", LastName="Hill" }
• };
• }
• Passing arrays to a method, the array is
declared with the parameter, as shown with
the method DisplayPersons() :
• void DisplayPersons(Person[] persons){}

You might also like