Presentation is loading. Please wait.

Presentation is loading. Please wait.

C# Language elements Arrays, Strings, Parameter Passing Jim Warren, COMPSCI 280 S2 2013 Enterprise Software Development.

Similar presentations


Presentation on theme: "C# Language elements Arrays, Strings, Parameter Passing Jim Warren, COMPSCI 280 S2 2013 Enterprise Software Development."— Presentation transcript:

1 C# Language elements Arrays, Strings, Parameter Passing Jim Warren, jim@cs.auckland.ac.nz COMPSCI 280 S2 2013 Enterprise Software Development

2 Outline COMPSCI2802  Learn to apply some fundamental aspects of C#  Arrays  Including arrays of objects and multidimensional Arrays  Strings  Create, manipulate and compare  Methods and parameters  Value and reference parameters  Static methods and fields

3 Arrays COMPSCI2803  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  Array elements  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.  Length  The number of elements in an array  It determines the amount of memory allocated for the array elements. (can’t be changed)  Index/Subscript  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:  Example: int[] hours; declares an array variable but does not assign an array to it = null 0 1 295 3 Array Name Index Value courseMarks[2]= 95;

4 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  To create an array and supply initial element values in the New clause  Declare a variable, create the array & initialization  Short cut:  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 00 10 20 COMPSCI2804 int[] nb1 = new int[3]; size string[] weekDays2 = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; int[] numbers2 = new int[3] {1, 2, 3}; Size = 3 Index: 0 to 2 int[] array3; //declare array3 = new int[] { 1, 3, 5, 7, 9 }; // OK //array3 = {1, 3, 5, 7, 9}; // Error

5 Using Arrays COMPSCI2805  To access the individual variables in an array though an index  Example:  Information:  To determine the number of elements of an array  To determine the highest subscript value (upper bound) of an array  Array processing is easily done in a loop  A for loop is commonly used,  You also can use foreach statement  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 nb1[0] = 1; Console.WriteLine(nb1.GetLength(0)) Console.WriteLine(nb1.Length) Console.WriteLine(nb1.GetUpperBound(0)) 3 2 Parameter: The dimension/rank 01 10 20 for (int i = 0; i < nb1.Length; i++) { numbers1[i] = i; } foreach (int x in nb1) Console.Write(x); Using ‘in’ – like the Python ‘for’ loop

6 Using Arrays (con’t) COMPSCI2806  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  Using the Array class  Provides methods for creating, manipulating, searching, and sorting arrays  Use Array.Sort method to sort arrays in ascending order  Use Array.Reverse method to reverse the order  Use Array.Copy method to copy an array  Parameters: the original, new array and the number of elements int[] numbersForSorting = {7, 12, 1, 6, 3} ; Array.Sort(numbersForSorting) ; string[] names = {"Sue", "Kim", "Alan", "Bill"}; Array.Sort(names); Array.Reverse(names); int[] copy = new int[3]; Array.Copy(nb1, copy, 3); int[] nb2; nb2 = nb1; nb2 nb1 00 11 22

7 Copying Arrays COMPSCI2807  Method 1:  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.  Method 3:  Use the CopyTo method from the original array  Parameters: the new array and the starting index  Method 4:  Use the Clone method from the original array  An array can be cloned to reproduce an exact copies of the original  Type casting is needed  Changing the contents of the copied object would not affect the contents of the source object Array.Copy(srcArray, srcIndex, destArray, destIndex, length); nb1 copy nb1[0] = 10; 00 11 22 00 11 22 nb1.CopyTo(copy, 0); copy = (int[])nb1.Clone();

8 Arrays of Objects COMPSCI2808  Apart from arrays of value types we can have arrays of reference types  Example:  To create an array of MyPoint elements  To create an array  Note: Memory space are allocated for the array  Each of which is initialized to a null reference  To create the object elements  Invoke the new keyword to create the MyPoint object  Note:  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. MyPoint[] src = new MyPoint[2]; 0 1 x=1,y=2 x=2,y=3 src src[0] = new MyPoint(1, 2); src[1] = new MyPoint(2, 3); A user-defined class with x and y fields or properties

9 Working with Arrays of Objects  Assigning arrays  The variable c1 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  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  Reference types still point to same objects  Type casting is needed COMPSCI2809 MyPoint[] c1; c1 = src; c1 0 1 x=1,y=2 x=2,y=3 src 0 1 c2 0 1 x=10,y=2 x=2,y=3 src MyPoint[] c2 = new MyPoint[2]; Array.Copy(src, c2, 2); src[0].x = 10; Console.WriteLine(c1 == src); MyPoint[] c3 = (MyPoint[]) src.Clone();

10 Multidimensional Arrays COMPSCI28010  You can declare arrays with up to 32 dimensions  A Two-dimensional array is like a table with rows and columns  A Three-dimensional array is like a cube,  with rows, columns, and pages  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 GetLength method  Note that the argument you pass to GetLength and GetUpperBound (the dimension for which you want the length or the highest subscript) is 0-based.  The highest subscript value is returned by the GetUpperBound method for that dimension.  The length property of the array is the total size of an array int[,] rectangle = new int[4, 5]; int[,,] cube = new int[5, 4, 5]; Console.WriteLine(rectangle.Length); Console.WriteLine(rectangle.GetLength(0)); Console.WriteLine(rectangle.GetUpperBound(0)); 20 4 3

11 Creating and Using 2D Arrays  Creating Arrays  To create an array using the New clause  Declare a variable, create the array and initialized with default values  To create an array and supply initial element values in the New clause  Accessing elements  To access elements, we use pretty much the same technique as a 1D array  Navigating elements  Nested loops are used to navigate the array elements 123 456 COMPSCI28011 double[,] weights = new double[2, 2]; int[,] nums2 = new int[,] { {1, 2, 3}, {4, 5, 6}}; int[,] nums3 = { { 1, 2, 3 }, { 4, 5, 6 } }; Console.WriteLine(nums2[rowToGet, colToGet]); for (int i = 0; i < nums2.GetLength(0); i++){ for (int j = 0; j < nums2.GetLength(1); j++) Console.Write(nums2[i, j] + " "); Console.WriteLine(); }

12 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 different sizes.  Creating Jagged Arrays  To create a Jagged Array  Declare a variable, create the array and initialized with default values  To create an array and supply initial element values in the New clause: 0 1 2 32 COMPSCI28012 int[][] b2 = new int[][] { new int[] {3,2}, new int[] {3,2,1}, new int[] {1}}; 321 1 b2 int[][] b = new int[3][]; b[0] = new int[2]; b[1] = new int[3]; b[2] = new int[1]; single-dimensional array that has three elements, each of which is a single- dimensional array of integers 0 1 2 00 000 0 b

13 Using Jagged Arrays COMPSCI28013  Length & UpperBound  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 GetUpperBound(0) method.  The length property of the jagged array returns the number of arrays contained in the jagged array.  The GetLength(0) method returns the number of elements  Accessing elements  This example, displays the value of the second element of the first array.  Navigating elements  Note: b2[i].GetLength(0) returns the number of the array element at the array index i for (int i = 0; i < b2.Length; i++){ for (int j = 0; j < b2[i].GetLength(0); j++) Console.Write(b2[i][j] + " "); Console.WriteLine(); } Console.WriteLine(b[0][1]); Number of arraysNumber of elements of the corresponding array contained in the jagged array

14 COMPSCI28014 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  Using literal  Using C# string constructors  Working with Strings  Escape Characters  \n, \t …  The @ Symbol  ignore escape characters and line breaks string greeting = "Hello"; string repeated = new string('c', 4); Console.WriteLine(repeated); char[] charArray = { 'h', 'e', 'l', 'l', 'o' }; string fromCharArray = new string(charArray); string hello = "Hello\nWorld!"; string p1 = "\\\\My Documents\\My Files\\"; string p2 = @"\\My Documents\My Files\";

15 COMPSCI28015 Strings Manipulation  Length  Returns the length of the string  Basic operations:  Retrieves a character  Using its index  Concatenate strings using the + operator  IndexOf()  To search for a string inside another string  Parameter: The String to seek.  returns  -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.WriteLine(greeting.Length); char a = greeting[0]; Console.WriteLine(greeting += a); string s1 = "Battle of Hastings, 1066"; Console.WriteLine(s1.IndexOf("Hastings")); Console.WriteLine(s1.IndexOf("1967")); Console.WriteLine(p1.Replace("Documents", "Pictures")); ‘H’ “HelloH” 10

16 COMPSCI28016 Strings Manipulation (con’t)  Trim()  Removes all occurrences of a set of specified characters from the beginning and end of this instance  No parameter: remove all white space  Parameter: the char to remove  SubString()  Retrieves a substring from this instance  Parameters: starting position and/or the length  Split  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 string s4 = "Visual C# Express"; Console.WriteLine(s4.Substring(7, 2)); char[] delimiter = new Char[] { ' ', '.' }; string words = "this is"; string[] split = words.Split(delimiter); this is string str1 = "*;|@123***456@|;*"; string delim = "*;|@"; string str2 = str1.Trim(delim.ToCharArray()); 123***456 C#

17 COMPSCI28017 Strings Manipulation (con’t)  Concat  Concatenates one or more instances of string  Join  Concatenates a specified separator String between each element of a specified String array, yielding a single concatenated string.  Parameters: separator and a string array  ToLower/ToUpper  Returns a copy of this String converted to lowercase/uppercase  ToCharArray  Copies the characters in this instance to a Unicode character array. Console.WriteLine(String.Concat(words, " good")); string[] s5 ={ "apple", "orange", "grape" }; Console.WriteLine(String.Join(", ", s5)); Static method apple, orange, grape Static method

18 COMPSCI28018 Strings Comparison  Equals  String.Equals(Object)  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  String.Equals(String, String)  Static method  Determines whether two specified String objects have the same value  Or use the equality/inequality operator (==, !=)  Which is NOT what you’d expect if you were comparing references to two arrays of characters  Use IsNullOrEmpty to check for a null reference or an empty string str1 = "ABCD"; str2 = "abcd"; Console.WriteLine(String.IsNullOrEmpty(str1)); Console.WriteLine(str1 == str2); Console.WriteLine(str1.Equals(str2)); Console.WriteLine(String.Equals(str1, str2)); Static method False

19 COMPSCI28019 Strings Comparison (con’t)  Using string.CompareTo  returns an integer value based on whether one string is less-than ( ) another.  Performs a word (case-sensitive and culture-sensitive) comparison using the current culture. (e.g. “a” < “A”)  Using string.Compare  Static method  Optional bool parameter to ignore case result = str1.CompareTo(str2); result = String.Compare(str1, str2, true); +ve

20 Methods  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  Its expression must conform to the return type COMPSCI 28020 public string GetStatus() {... return...; }

21 Passing mechanism COMPSCI 28021  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  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.

22 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  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 COMPSCI 28022 public static void UpdateIntByValue(int v){ v *= 2; } public static void UpdateIntByRef(ref int v) { v *= 3; } int x1 = 1; UpdateIntByValue(x1); Console.WriteLine(x1); int x2=1, x3=1; UpdateIntByRef(ref x2); UpdateIntByOut(out x3); 1 (unchanged) 3 (changed) public static void UpdateIntByOut(out int v) { v = 4; } 4 changed x2 must be initialised. required to assign a value before the method returns

23 Passing Reference-Type COMPSCI 28023  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  B) The method cannot change the variable  Example: you cannot assign a new array to the variable public static void UpdateRefTypeByValue(int[] x){ x[0] = 10; } int[] y1 = { 1, 2, 3 }; UpdateRefTypeByValue(y1); Console.WriteLine(y1[0]); =10 public static void ReplaceRefTypeByValue(int[] x) { x = new int[] { 2, 3 }; } int[] y2 = { 1, 2, 3 }; ReplaceRefTypeByValue(y2); Console.WriteLine(y2[0]); =1 Changed array is not passed back to caller

24 Passing Reference Type COMPSCI 28024  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  B) The method can also change the variable  Example: you can assign a new array to the variable public static void UpdateRefTypeByRef(ref int[] x){ x[0] = 10; } int[] y3 = { 1, 2, 3 }; UpdateRefTypeByRef( ref y3); Console.WriteLine(y3[0]); =10 public static void ReplaceRefTypeByRef(ref int[] x){ x = new int[] {2,3}; } int[] y4 = { 1, 2, 3 }; ReplaceRefTypeByRef(ref y4); Console.WriteLine(y4[0]); =2 change the entire array change the member

25 Parameters Arrays COMPSCI 28025  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.  To call the method:  No parameter — that is, you can omit the argument  By a list of an indefinite number of arguments  By an array with the same element type  See http://msdn.microsoft.com/en-us/library/aa645765(v=vs.71).aspxhttp://msdn.microsoft.com/en-us/library/aa645765(v=vs.71).aspx public static void PrintChars(params char[] chars) { foreach (char c in chars) Console.Write(c + " "); } PrintChars(); PrintChars('a'); PrintChars('a', 'b'); PrintChars(new char[] { '1', '2' });

26 The this keyword COMPSCI 28026  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  To pass an object as a parameter to other methods  To invoke another constructor in the same object from a constructor public Employee(string name, string alias) { this.name = name; this.alias = alias; } Refers to the argument from the method call public MyPoint(): this(0,0) {... } CalcTax(this); A ‘constructor’ is a method with the same name as its class; run when someone wants a ‘new’ instance of that class

27 Static Classes COMPSCI 28027  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 CompanyInfo { public static string GetCompanyName() { return "CompanyName"; } public static string GetCompanyAddress() { return "CompanyAddress"; } //... }

28 Static Fields & Methods COMPSCI 28028  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  Static methods and properties can only access static fields class MyCounter { public static int Count; public int value; public MyCounter() { Count += 1; } public MyCounter(int i) { value = i; Count += 1; } MyCounter obj1 = new MyCounter(1); MyCounter obj2 = new MyCounter(2); Console.WriteLine(MyCounter.Count);

29 Overloading COMPSCI 28029  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.  Note: methods cannot be overloaded if one method takes a ref argument and the other takes an out argument public static void Display(char theChar) { Console.WriteLine("The char"); } public static void Display(int theInteger) { Console.WriteLine("The Integer"); } public static void Display(double theDouble) { Console.WriteLine("The Double"); } public static void Display(ref char theChar) {} public static void Display(out char theChar) {} public static void Display(int theInt) {} public static void Display(ref int theInt) {} ERROR! OK!

30 Conclusion  We’ve now learned some C# language basics  Next – we’ll learn to connect work with a database from C# /.NET Handout 03COMPSCI28030


Download ppt "C# Language elements Arrays, Strings, Parameter Passing Jim Warren, COMPSCI 280 S2 2013 Enterprise Software Development."

Similar presentations


Ads by Google