COMPSCI 280 S 2 2013 Enterprise Software Development


![Array Name Arrays course. Marks[2]= 95; 2 All of the variables within an array Array Name Arrays course. Marks[2]= 95; 2 All of the variables within an array](https://slidetodoc.com/presentation_image/9ef03f8ffdcc7c77d9356255855186a0/image-3.jpg)





![Working with Arrays of Objectssrc Assigning arrays My. Point[] c 1; c 1 = Working with Arrays of Objectssrc Assigning arrays My. Point[] c 1; c 1 =](https://slidetodoc.com/presentation_image/9ef03f8ffdcc7c77d9356255855186a0/image-9.jpg)





















- Slides: 30
COMPSCI 280 S 2 2013 Enterprise Software Development C# Language elements Arrays, Strings, Parameter Passing Jim Warren, jim@cs. auckland. ac. nz
Outline Learn to apply some fundamental aspects of C# Arrays Strings Create, manipulate and compare Methods and parameters 2 Including arrays of objects and multidimensional Arrays Value and reference parameters Static methods and fields COMPSCI 280
Array Name Arrays course. Marks[2]= 95; 2 All of the variables within an array are called elements and are of the same data type The default value of numeric array elements are set to zero, and reference elements are set to null. The number of elements in an array It determines the amount of memory allocated for the array elements. (can’t be changed) You can access the individual variables in an array though an index or subscript Subscript numbering begins at 0 and goes to the last element in an array (length minus one) Array Dimensions The dimensionality or rank corresponds to the number of subscripts used to identify an individual element. (max=32) Array types are reference types derived from the abstract base type Array Declaring Arrays: 3 Index/Subscript 95 Length 1 Array elements 3 Value 0 Arrays allow you to refer to a series of variables by the same name An array can be Single-Dimensional, Multidimensional or Jagged. Array Overview Index Example: int[] hours; declares an array variable but does not assign an array to it = null COMPSCI 280
Creating Arrays To create an array using the New clause Declare a variable, create the array & initialize the array elements to their default values Memory space allocated Array elements are initialize to their default values int[] nb 1 = new int[3]; size Size = 3 Index: 0 to 2 0 0 1 0 2 0 To create an array and supply initial element values in the New clause Declare a variable, create the array & initialization int[] numbers 2 = new int[3] {1, 2, 3}; Short cut: string[] week. Days 2 = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; Note: It is possible to declare an array variable without initialization, but you must use the new operator when you assign an array to this variable int[] array 3; //declare array 3 = new int[] { 1, 3, 5, 7, 9 }; //array 3 = {1, 3, 5, 7, 9}; 4 // OK // Error COMPSCI 280
Using Arrays To access the individual variables in an array though an index 0 1 1 0 2 0 Example: Information: nb 1[0] = 1; 3 To determine the number of elements of an array Console. Write. Line(nb 1. Get. Length(0)) Console. Write. Line(nb 1. Length) Parameter: The dimension/rank To determine the highest subscript value (upper bound) of an array Console. Write. Line(nb 1. Get. Upper. Bound(0)) Array processing is easily done in a loop A for loop is commonly used, for (int i = 0; i < nb 1. Length; i++) { numbers 1[i] = i; } Using ‘in’ – like the Python ‘for’ loop foreach (int x in nb 1) Console. Write(x); You also can use foreach statement 5 2 It runs the statement block for each element in a collection, instead of a specified number of times. It uses an element variable that represents a different element of the collection during each repetition of the loop COMPSCI 280
Using Arrays (con’t) Assigning Arrays The new array variable holds a copy of the reference held in the variable numbers. So, there is still only one copy of the array nb 1 int[] nb 2; nb 2 = nb 1; Using the Array class nb 2 0 0 1 1 2 2 Provides methods for creating, manipulating, searching, and sorting arrays Use Array. Sort method to sort 12, arrays ascending order int[] numbers. For. Sorting = {7, 1, 6, in 3} ; Array. Sort(numbers. For. Sorting) ; string[] names = {"Sue", "Kim", "Alan", "Bill"}; Array. Sort(names); Array. Reverse(names); Use Array. Reverse method to reverse the order int[] Use Array. Copy method to copy an array copy = new int[3]; Array. Copy(nb 1, copy, 3); 6 Parameters: the original, new array and the number of elements COMPSCI 280
nb 1 Copying Arrays Method 1: copy 0 0 1 1 2 2 Copy the elements one at a time in a loop Method 2: Use the Array. Copy method It Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. Array. Copy(src. Array, src. Index, dest. Array, dest. Index, length); Method 3: Use the Copy. To method from the original array Method 4: Use the Clone method from the original array 7 Parameters: the new array and the starting index nb 1. Copy. To(copy, 0); An array can be cloned to reproduce an exact copies of the original Type casting is needed copy = (int[])nb 1. Clone(); Changing the contents of the copied object would not affect the contents of the source object nb 1[0] = 10; COMPSCI 280
Arrays of Objects Apart from arrays of value types we can have arrays of reference types A user-defined class with x and y fields or properties Example: To create an array of My. Point elements To create an array My. Point[] src = new My. Point[2]; Note: 8 0 x=1, y=2 1 x=2, y=3 To create the object elements Note: Memory space are allocated for the array Each of which is initialized to a null reference src Invoke the new keyword to create the My. Point object src[0] = new My. Point(1, 2); src[1] = new My. Point(2, 3); In an array of reference types the objects are not stored in the array; but rather, references to the objects are stored in the array. The objects themselves have to be created and memory space has to be allocated for them separately. COMPSCI 280
Working with Arrays of Objectssrc Assigning arrays My. Point[] c 1; c 1 = src; 1 x=2, y=3 My. Point[] c 2 = new My. Point[2]; Array. Copy(src, c 2, 2); Use Array. Copy to copy arrays However both source and destination elements now refer to the same object (pointing to the same physical object in memory) Thus changing the element will also cause the contents of the other variable to change Cloning – Shallow clone only src[0]. x = 10; Reference types still point to same objects Type casting is needed src My. Point[] c 3 = (My. Point[]) src. Clone(); 9 x=1, y=2 The variable c 1 holds a copy of the reference held in the variable src. There is still only one copy of the array. Thus changing the object pointed to by one of the variables will also cause the contents of the other variable to change Copying arrays c 1 Console. Write. Line(c 1 == src); 0 COMPSCI 280 0 x=10, y=2 0 1 x=2, y=3 1 c 2
Multidimensional Arrays You can declare arrays with up to 32 dimensions A Two-dimensional array is like a table with rows and columns int[, ] rectangle = new int[4, 5]; A Three-dimensional array is like a cube, with rows, columns, and pages int[, , ] cube = new int[5, 4, 5]; Overview The rank/dimension of an array is held in its Rank property The lowest subscript value for a dimension is always 0 The length of each dimension is returned by the Get. Length method Note that the argument you pass to Get. Length and Get. Upper. Bound (the dimension for which you want the length or the highest subscript) is 0 -based. The highest subscript value is returned by the Get. Upper. Bound method for that dimension. The length property of the array is the total size of an array Console. Write. Line(rectangle. Length); Console. Write. Line(rectangle. Get. Length(0)); Console. Write. Line(rectangle. Get. Upper. Bound(0)); 10 COMPSCI 280 20 4 3
Creating and Using 2 D Arrays Creating Arrays To create an array using the New clause Declare a variable, create the array and initialized with default values double[, ] weights = new double[2, 2]; int[, ] nums 2 = new int[, ] { {1, 2, 3}, {4, 5, 6}}; 1 2 3 int[, ] nums 3 = { { 1, 2, 3 }, { 4, 5, 6 } }; 4 5 6 Accessing elements Console. Write. Line(nums 2[row. To. Get, To create an array and supply initial element values in the New clause To access elements, we use pretty much the same technique as a 1 D array Navigating elements Nested loops are used to navigate the array elements for (int i = 0; i < nums 2. Get. Length(0); i++){ for (int j = 0; j < nums 2. Get. Length(1); j++) Console. Write(nums 2[i, j] + " "); Console. Write. Line(); } 11 col. To. Get]); COMPSCI 280
Jagged Arrays An array of which each element is itself an array is called an array of arrays. The elements of a jagged array can be of b 0 0 different sizes. 0 0 0 1 Creating Jagged Arrays 2 To create a Jagged Array Declare a variable, create the array and initialized withb 2 default int[][] b = new int[3][]; single-dimensional array that 0 b[0] = new int[2]; has three elements, b[1] = new int[3]; 1 each of which is a singleb[2] = new int[1]; 2 dimensional array of integers 0 values 3 2 12 COMPSCI 280 1 1 To create an array and supply initial element values in the New int[][] b 2 = new int[][] { new int[] {3, 2}, new int[] {3, 2, 1}, new int[] clause: 0 {1}};
Using Jagged Arrays Length & Upper. Bound The jagged array is ONE dimension only. Each element of the jagged array is itself an array. The rank/dimension of an array is held in its Rank property. The highest subscript value is returned by the Get. Upper. Bound(0) method. The length property of the jagged array returns the number of arrays contained in the jagged array. The Get. Length(0) method returns the number of elements Accessing elements This example, displays the value of the second element of the first array. Console. Write. Line(b[0][1]); Navigating elements Note: b 2[i]. Get. Length(0) returns the number of the array element at the array index i Number of arrays 13 Number of elements of the corresponding array contained for (int i = 0; i < b 2. Length; i++){ in the jagged array for (int j = 0; j < b 2[i]. Get. Length(0); j++) Console. Write(b 2[i][j] + " "); Console. Write. Line(); } COMPSCI 280
Strings A C# string is an array of characters declared using the string keyword. string is an alias for String in the. NET Framework. String objects are read-only and immutable, meaning that they cannot be changed once they have been created. Creating strings string greeting = "Hello"; Using literal Using C# string constructors string repeated = new string('c', 4); Console. Write. Line(repeated); char[] char. Array = { 'h', 'e', 'l', 'o' }; string from. Char. Array = new string(char. Array); Working with Strings Escape Characters The @ Symbol 14 n, t … string hello = "Hellon. World!"; string p 1 = "\\My Documents\My Files\"; string p 2 = @"\My DocumentsMy Files"; ignore escape characters and line breaks COMPSCI 280
Strings Manipulation Length Returns the length of the string Basic operations: Retrieves a character char a = greeting[0]; Console. Write. Line(greeting += a); ‘H’ “Hello. H” Using its index Concatenate strings using the + operator Index. Of() 10 -1 To search for a string inside another string s 1 = "Battle of Hastings, 1066"; Parameter: The String to seek. Console. Write. Line(s 1. Index. Of("Hastings")); returns Console. Write. Line(greeting. Length); Console. Write. Line(s 1. Index. Of("1967")); -1 if not found the zero-based index of the first location at which it occurs. Replace() Replaces all occurrences of a specified char or String in this instance, with another specified Unicode character or String. Console. Write. Line(p 1. Replace("Documents", "Pictures")); 15 COMPSCI 280
Strings Manipulation (con’t) Trim() Sub. String() Removes all occurrences of a set of specified characters from the beginning and end of this instance No parameter: remove all white space 123***456 Parameter: the char to remove Retrieves a substring from this instance Parameters: starting position and/or the length Split string str 1 = "*; |@123***456@|; *"; string delim = "*; |@"; string str 2 = str 1. Trim(delim. To. Char. Array()); C# string s 4 = "Visual C# Express"; Console. Write. Line(s 4. Substring(7, 2)); Returns a String array containing the substrings in this instance that are delimited by elements of a specified Char or String array. Parameter: delimiter elements char[] delimiter = new Char[] { ' ', '. ' }; string words = "this is"; this string[] split = words. Split(delimiter); is 16 COMPSCI 280
Strings Manipulation (con’t) Concatenates one or more instances of string Console. Write. Line(String. Concat(words, " good")); Join Static method Concatenates a specified separator String between each element of a specified String array, yielding a single concatenated string. Parameters: separator and a string array string[] s 5 ={ "apple", "orange", "grape" }; Console. Write. Line(String. Join(", ", s 5)); To. Lower/To. Upper Returns a copy of this String converted to lowercase/uppercase To. Char. Array 17 apple, orange, grape Static method Copies the characters in this instance to a Unicode character array. COMPSCI 280
Strings Comparison Equals String. Equals(Object) String. Equals(String, String) Static method Determines whether two specified String objects have the same value Or use the equality/inequality operator (==, !=) Determines whether this instance of String and a specified object, which must also be a String object, have the same value (value equality) This method performs an ordinal (case-sensitive) comparison Which is NOT what you’d expect if you were comparing references to two arrays of characters Use Is. Null. Or. Empty to check for a null reference or an empty Static str 1 = "ABCD"; string method str 2 = "abcd"; Console. Write. Line(String. Is. Null. Or. Empty(str 1)); Console. Write. Line(str 1 == str 2); False Console. Write. Line(str 1. Equals(str 2)); Console. Write. Line(String. Equals(str 1, str 2)); 18 COMPSCI 280
Strings Comparison (con’t) Using string. Compare. To result = str 1. Compare. To(str 2); returns an integer value based on whether one string is less-than (<)or greater-than (>) another. Performs a word (case-sensitive and culture-sensitive) comparison using the current culture. (e. g. “a” < “A”) Using string. Compare 19 +ve result = String. Compare(str 1, Static method Optional bool parameter to ignore case COMPSCI 280 str 2, true);
Methods are made up of a block of code that performs one specific action Methods can affect the values of properties A method definition has two parts: a method declaration and a method body Methods are declared within a class by specifying the access level, the return value, the name of the method, and any method parameters. The method parameter specifies the type and name of each parameter The return type indicates the type of value that the methods sends back to the calling location A method that does not return a value has a void return type A method body is where all the action takes place. It contains the instructions that implement the method The return statement specifies the value to be returned 20 public string Get. Status() {. . . return. . . ; } Its expression must conform to the return type COMPSCI 280
Passing mechanism A method may modify the programming element underlying the argument in the calling code. It depends on the following: The argument is being passed by value or by reference The argument data type is a value type or a reference type The default is to pass arguments by value Passing parameters by reference Change the value of the parameters and have that change persist Use the ref or out keywords 21 Note: ref requires that the variable be initialized before being passed. Note: out arguments need not be initialized prior to being passed but calling method is required to assign a value before the method returns. COMPSCI 280
Passing Value-Type Parameters Case 1: value Type + Pass by value Passing a copy of the variable to the method The method cannot modify the variable itself int x 1 = 1; Update. Int. By. Value(x 1); Console. Write. Line(x 1); 1 (unchanged) public static void Update. Int. By. Value(int v){ v *= 2; } Case 2: value Type + Passy by reference (ref/out) Reference is passed into the method Both the method definition and the calling method must explicitly use the ref/out keyword. The method can modify the variable itself x 2 must be 3 initialised. (changed) public static void Update. Int. By. Ref(ref int v) { v *= 3; 4 } changed int x 2=1, x 3=1; Update. Int. By. Ref(ref x 2); Update. Int. By. Out(out x 3); 22 public static void Update. Int. By. Out(out int v) { v = 4; required to assign a value COMPSCI 280 } before the method returns
Passing Reference-Type Case 3: Reference Type + Pass by value The method cannot change the variable but can change members of the instance to which it points A) The method can change the members int[] y 1 = { 1, 2, 3 }; Update. Ref. Type. By. Value(y 1); Console. Write. Line(y 1[0]); =10 public static void Update. Ref. Type. By. Value(int[] x){ x[0] = 10; } B) The method cannot change the variable Example: you cannot assign a new array to the variable int[] y 2 = { 1, 2, 3 }; Replace. Ref. Type. By. Value(y 2); Console. Write. Line(y 2[0]); =1 23 public static void Replace. Ref. Type. By. Value(int[] x) { x = new int[] { 2, 3 }; } Changed array is not passed back to caller COMPSCI 280
Passing Reference Type Case 4: Reference Type + Pass by Reference The method can change both the variable and members of the instance to which it points A) The method can change the members int[] y 3 = { 1, 2, 3 }; Update. Ref. Type. By. Ref( ref y 3); Console. Write. Line(y 3[0]); =10 public static void Update. Ref. Type. By. Ref(ref int[] x){ x[0] = 10; change the } member B) The method can also change the variable Example: you can assign a new array to the variable int[] y 4 = { 1, 2, 3 }; Replace. Ref. Type. By. Ref(ref y 4); Console. Write. Line(y 4[0]); =2 24 public static void Replace. Ref. Type. By. Ref(ref int[] x){ x = new int[] {2, 3}; } change the COMPSCI 280 entire array
Parameters Arrays When you need an indefinite number of arguments, you can declare a parameter array Use the params keyword in a method declaration Rules: A method can have only one parameter array (one-dimensional), and it must be the last argument in the procedure definition. The parameter array must be passed by value. public static void Print. Chars(params char[] chars) { foreach (char c in chars) Console. Write(c + " "); } To call the method: No parameter — that is, you can omit the Print. Chars(); Print. Chars('a'); argument Print. Chars('a', 'b'); By a list of an indefinite number of Print. Chars(new char[] arguments By an array with the same element type See http: //msdn. microsoft. com/en-us/library/aa 645765(v=vs. 71). aspx 25 COMPSCI 280 { '1', '2' });
The this keyword refers to the current instance of the class It is useful if you have name clashes between the parameter name and your internal variable public Employee(string name, string alias) { this. name = name; this. alias = alias; Refers to the argument } from the method call To pass an object as a parameter to other methods Calc. Tax(this); To invoke another constructor in the same object from a public My. Point(): this(0, 0) { constructor. . . } 26 A ‘constructor’ is a method with the same name as its class; run when someone COMPSCI 280 wants a ‘new’ instance of that class
Static Classes Note: Methods and properties are only available after creating an instance of the class Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class Static methods can be invoked directly from the class (not from a specific instance of a class) Rules: Static classes contain static members Static classes cannot be instantiated static class Company. Info { public static string Get. Company. Name() { return "Company. Name"; } public static string Get. Company. Address() { return "Company. Address"; } //. . . } 27 COMPSCI 280
Static Fields & Methods Static Fields An instance field has one copy for each object of the class. But a static field has one copy for all objects of a class. They share a value across all instances of a class. It is useful if we want to total or count the number of objects for a class Static methods and properties can only access static fields class My. Counter { public static int Count; public int value; public My. Counter() { Count += 1; } public My. Counter(int i) { value = i; Count += 1; } } 28 My. Counter obj 1 = new My. Counter(1); My. Counter obj 2 = new My. Counter(2); Console. Write. Line(My. Counter. Count); COMPSCI 280
Overloading is the creation of more than one methods, instance constructors, or properties in a class with the same name but different argument types. At run time, the system calls the correct method based on the data types of the parameters you specify. public static void Display(char the. Char) { Console. Write. Line("The char"); } public static void Display(int the. Integer) { Console. Write. Line("The Integer"); } public static void Display(double the. Double) { Console. Write. Line("The Double"); } Note: methods cannot be overloaded if one method takes a ref argument OK! and the other takes an out argument public static void Display(int the. Int) {} public static void Display(ref char the. Char) {} public static void Display(out char the. Char) {} 29 ERROR! COMPSCI 280
Conclusion 30 We’ve now learned some C# language basics Next – we’ll learn to connect work with a database from C# /. NET COMPSCI 280 Handout 03