C#Programming Arrays in C#Declaring Arrays of Different TypesInitializing ArrayAccessing Array ElementsCreating User Interfaces Using Windows Standards Form Application Types and StandardsLooking at FormsWeek 5
2
ARRAYSThe array is the most common data
structure, found in all programming languages.
Using an array in C# involves creating an array object of System.Array type, the abstract base type for all arrays.
The Array class provides a set of methods for performing tasks such as sorting and searching that programmers had to build by hand in the past.
3
ArraysAn interesting alternative to using
arrays in C# is the ArrayList class. An arrayList is an array that grows dynamically as more space is needed. For situations where you can’t accurately determine the ultimate size of an array, or where the size of the array will change quite a bit over the lifetime of a program, an arrayList may be a better choice than an array.
4
ArraysArrays are indexed collections of data. The data
can be of either a built-in type or a user-defined type.
In fact, it is probably the simplest just to say that array data are objects.
Arrays in C# are actually objects themselves because they derive from the System.Array class.
An array is a declared instance of the System.Array class, so we can use of all the methods and properties of this class when using arrays
In C#, arrays can be declared as fixed length or dynamic.
5
Declaring and Initializing ArraysArrays are declared using the
following syntax:type[] array-name;where type is the data type of
the array elements. Here is an example:
int[ ] intArray; intArray = new int[5];
6
Defining arrays of different typesIn C#, arrays are objects. That means that
declaring an array doesn't create an array. After declaring an array, you need to instantiate an array by using the "new" operator.
The following syntax defines arrays of different data types
double[] doubleArray = new double[5]; char[] charArray = new char[5]; bool[] boolArray = new bool[2]; string[] stringArray = new string[10];
7
Initializing Arrays Once an array is declared, the next step is to initialize an
array. The initialization process of an array includes adding actual data to the array.
The following sample syntaxes creates an array of 3 items and values of these items are added when the array is initialized.
int[] sArray = new int[3] {1, 3, 5};
Alternative, we can also add array items one at a time as listed in the following code snippet.
int[ ] sArray = new int[3]; sArray[0] = 1; sArray[1] = 3; sArray[2] = 5;
8
Initializing ArraysThe following code declares a static type of array with integer values. int[ ] x=new int[ ] {1,3,4,5,6}; Console.WriteLine(x[3]); Console.ReadLine();The following code declares a dynamic array with string values. string[ ] strArray = new string[] { “kamal",
“Ali", “Raheel", "Praveen", “Mujeeb" };
9
Accessing ArraysWe can access an array item by passing the
item index in the array. The following syntax creates an array of three
items and displays those items on the console. ◦ int[] staticIntArray = new int[3]; ◦ staticIntArray[0] = 1; ◦ staticIntArray[1] = 3; ◦ staticIntArray[2] = 5;
◦ Console.WriteLine(staticIntArray[0]); ◦ Console.WriteLine(staticIntArray[1]); ◦ Console.WriteLine(staticIntArray[2]);
10
Accessing an array using a foreach Loop The foreach control statement is used to iterate through
the items of an array. For example, the following code uses foreach loop to read
all items of an array of strings.
string[ ] strArray = new string[] { “kamal", “Ali", “Raheel", "Praveen", “Mujeeb" };
foreach (string str in strArray) { Console.WriteLine(str); } The following code will access the elements of integer type
array foreach (int x in myArray) { Console.WriteLine(x); }
11
Setting and Accessing Array ElementsElements are stored in an array either by direct
access or by calling the Array class method SetValue. Direct access involves referencing an array position by index on the left-hand side of an assignment statement:◦ Names[2] = "Raymond";◦ Sales[19] = 23123;
The SetValue method provides a more object-oriented way to set the value of an array element. The method takes two arguments, an index number and the value of the element.◦ names.SetValue["Raymond“,2];◦ sales.SetValue[23123,5];
12
Setting and Accessing Array Elements Array elements are accessed either by direct access
or by calling the GetValue method. The GetValue method takes a single argument—an index.◦ myName = names[2];◦ monthSales = sales.GetValue[19];◦ Console.WriteLine(sales.GetValue[2]);
It is common to loop through an array in order to access every array element using a For loop.
A frequent mistake programmers make when coding the loop is to either hard-code the upper value of the loop call a function that accesses the upper bound of the loop for each iteration of the loop:◦ (for int i = 0; i <= sales.GetUpperBound(0); i++)◦ totalSales = totalSales + sales[i];
13
Methods and Properties for Retrieving Array MetadataThe Array class provides several properties
for retrieving metadata about an arrayLength: Returns the total number of
elements in all dimensions of an array.GetLength: Returns the number of
elements in specified dimension of an arrayRank: Returns the number of dimensions of
an array GetType: Returns the Type of the current
array instance
14
Assignment 2Write a program in which all the
following functions using two different data types of arrays.
i.e. length, rank, getlength, get type
15
Array TypesArrays can be divided into the
following four categories. ◦Single-dimensional arrays ◦Multidimensional arrays or
rectangular arrays ◦Jagged arrays ◦Mixed arrays.
16
Single Dimension ArraysSingle-dimensional arrays are the
simplest form of arrays. These types of arrays are used to store number of items of a predefined type. All items in a single dimension array are stored contiguously starting from 0 to the size of the array -1.
The following code declares an integer array that can store 3 items. ◦ int[] intArray; ◦ intArray = new int[3];
17
Multi-Dimensional ArraysA multi-dimensional array, also known as a
rectangular array is an array with more than one dimension. The form of a multi-dimensional array is a matrix.
Syntax◦ int[ , ] xarray=new int[row,col];
Declaring a multi-dimensional array A multi dimension array is declared as
following: ◦string[,] mutliDimStringArray; ◦A multi-dimensional array can be fixed-sized or
dynamic sized.
18
Initializing multi-dimensional arraysThe following code is an example of
fixed-sized multi-dimensional arrays that defines two multi dimension arrays with a matrix of 3x2 and 2x2.
The first array can store 6 items and second array can store 4 items. Both of these arrays are initialized during the declaration. ◦ int[,] numbers = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } }; ◦ string[,] names = new string[2, 2] { { “Isb", “Lhr” }, { “DHA",
“Gulbarg" } };
19
Accessing multi-dimensional arraysA multi-dimensional array items are
represented in a matrix format and to access it's items, we need to specify the matrix dimension.
The following code shows how to access numbers array defined in the above code. ◦ Console.WriteLine(numbers[0,0]); ◦ Console.WriteLine(numbers[0, 1]); ◦ Console.WriteLine(numbers[1, 0]); ◦ Console.WriteLine(numbers[1, 1]); ◦ Console.WriteLine(numbers[2, 0]); ◦ Console.WriteLine(numbers[2, 2])
20
Parameter Arrays A parameter array is specified in the parameter list
of a method definition by using the keyword ParamArray.
The following method definition allows any amount of numbers to be supplied as parameters, with the total of the numbers returned from the method
◦ static int sumNums(params int[] nums) {int sum = 0;for(int i = 0; i <= nums.GetUpperBound(0); i++)sum += nums[i];return sum;}
21
Jagged ArraysData comes in various shapes.
Sometimes the shape is uneven. The C# language provides
jagged arrays, which can store efficiently many rows of varying lengths.
Any type of data, reference or value, can be used.
22
Initializing Jagged Arrays Jagged array can be used, its items must be initialized. The following code initializes a jagged array;
◦ intJaggedArray[0] = new int[2]; ◦ intJaggedArray[1] = new int[4]; ◦ intJaggedArray[2] = new int[6];
We can also initialize a jagged array's items by providing the values of the array's items.
The following code initializes item an array's items directly during the declaration.
◦ intJaggedArray[0] = new int[2]{2, 12}; ◦ intJaggedArray[1] = new int[4]{4, 14, 24, 34}; ◦ intJaggedArray[2] = new int[6] {6, 16, 26, 36, 46, 56 };
23
Accessing Jagged Arrays We can access jagged array using loop through all
of the items of a jagged array. The Length property of an array helps a lot; it gives
us the number of items in an array. The following code loops through all of the items of
a jagged array and displays them on the screen. for (int i = 0; i < intJaggedArray3.Length; i++) { System.Console.Write("Element({0}): ", i); for (int j = 0; j < intJaggedArray3[i].Length; j++) { System.Console.Write("{0}{1}", intJaggedArray3[i][j], j == (intJaggedArray3[i].Length - 1) ? "" : " "); } System.Console.WriteLine(); }
24
Accessing Jagged Arraysusing System; class Program { static void Main() { int[ ][ ] jagged = new int[3][ ]; jagged[0] = new int[2]; jagged[0][0] = 1; jagged[0][1] = 2;jagged[1] = new int[1];jagged[2] = new int[3] { 3, 4, 5 };for (int i = 0; i < jagged.Length; i++) { int[] innerArray = jagged[i]; for (int a = 0; a < innerArray.Length; a++) { Console.Write(innerArray[a] + " "); } Console.WriteLine(); }Console.ReadLine(); }
Output"1 2" "0" "3 4 5"
25
Mixed ArraysMixed arrays are a combination
of multi-dimension arrays and jagged arrays. The mixed arrays type is removed from .NET 4.0.