1 Console methods Write and WriteLine also have the capability to display formatted data. Figure 3.17 shows another way to use the WriteLine method. Outline Welcome4.cs Fig | Displaying multiple lines of text with string formatting. Method WriteLine ’s first argument is a format string that may consist of fixed text and format items. 3.5 Formatting Text with Console.Write and Console.WriteLine
2 Outline Addition.cs (1 of 2 ) Fig | Displaying the sum of two numbers input from the keyboard. (Part 1 of 2). Console. ReadLine() reads the data entered by the user, and Convert.ToInt32 converts the value into an integer. Three variables declared as type int. The user is prompted for information.
3 Outline Addition.cs (2 of 2 ) Fig | Displaying the sum of two numbers input from the keyboard. (Part 2 of 2).
4 Class GradeBook (Fig. 4.7) maintains the course name as an instance variable so that it can be used or modified. Outline GradeBook.cs (1 of 2 ) Fig. 4.7 | GradeBook class that contains a private instance variable, courseName and a public property to get and set its value. (Part 1 of 2). Declaring courseName as an instance variable.
5 Outline GradeBook.cs (2 of 2 ) Fig. 4.7 | GradeBook class that contains a private instance variable, courseName and a public property to get and set its value. (Part 2 of 2). A public property declaration.
6 Class GradeBookTest (Fig. 4.8) creates a GradeBook object and demonstrates property CourseName. Outline GradeBookTest.cs (1 of 2 ) Fig. 4.8 | Create and manipulate a GradeBook object. (Part 1 of 2). Creating a GradeBook object and assigning it to local variable myGradeBook. A public property declaration.
7 Outline GradeBookTest.cs (2 of 2 ) Calling DisplayMessage for a welcome message. Fig. 4.8 | Create and manipulate a GradeBook object. (Part 2 of 2). Assigns the input course name to myGradeBook ’s CourseName property.
8 Figure 4.10 redefines class GradeBook with an auto- implemented CourseName property. Outline GradeBook.cs Fig | GradeBook class with an auto-implemented property. Declaring the auto- implemented property. Implicitly obtaining the property’s value.
9 Class GradeBookTest (Fig. 4.8) creates a GradeBook object and demonstrates property CourseName. Outline GradeBookTest.cs (1 of 2 ) Fig. 4.8 | Create and manipulate a GradeBook object. (Part 1 of 2). Creating a GradeBook object and assigning it to local variable myGradeBook. A public property declaration.
10 Outline GradeBookTest.cs (2 of 2 ) Calling DisplayMessage for a welcome message. Fig. 4.8 | Create and manipulate a GradeBook object. (Part 2 of 2). Assigns the input course name to myGradeBook ’s CourseName property.
11 A class named Account (Fig. 4.17) maintains the balance of a bank account. Outline Account.cs (1 of 2 ) Fig | Account class with a constructor to initialize instance variable balance. (Part 1 of 2). An instance variable represents each Account ’s own balance. The constructor receives a parameter that represents the account’s starting balance. Method Credit receives one parameter named amount that is added to the property Balance.
12 Outline Account.cs (2 of 2 ) Fig | Account class with a constructor to initialize instance variable balance. (Part 2 of 2). Balance ’s get accessor returns the value of the Account ’s balance. Balance ’s set accessor performs validation to ensure that value is nonnegative.
13 AccountTest (Fig. 4.18) creates two Account objects and initializes them with 50.00M and M (decimal literals). Outline AccountTest.cs (1 of 3 ) Fig | Create and manipulate an Account object. (Part 1 of 3). Passing an initial balance which will be invalidated by Balance ’s set accessor. Outputting the Balance property of each Account.
14 Outline AccountTest.cs (2 of 3 ) Fig | Create and manipulate an Account object. (Part 2 of 3). Local variable deposit Amount is not initialized to 0 but will be set by the user’s input. Obtaining input from the user. Obtaining the deposit value from the user.
15 Outline AccountTest.cs (3 of 3 ) Fig | Create and manipulate an Account object. (Part 3 of 3). Outputting the balances of both Account s.
Floating-Point Numbers and Type decimal (Cont.) A value output with the format item {0:C} appears as a monetary amount. The : indicates that the next character represents a format specifier.
17 Fig | string format specifiers Floating-Point Numbers and Type decimal (Cont.)
18 Why Is Method Main Declared static ? The Main method is sometimes called the application’s entry point. Declaring Main as static allows the execution environment to invoke Main without creating an instance of the class. When you execute your application from the command line, you type the application name, followed by command-line arguments that specify a list of string s separated by spaces. The execution environment will pass these arguments to the Main method of your application. 7.3 static Methods, static Variables and Class Math (Cont.)
19 Additional Comments about Method Main Applications that do not take command-line arguments may omit the string[] args parameter. The public keyword may be omitted. You can declare Main with return type int (instead of void ) to enable Main to return an error code with the return statement. You can declare only one Main method in each class. 7.3 static Methods, static Variables and Class Math (Cont.)
20 You can place a Main method in every class you declare. However, you need to indicate the application’s entry point. Do this by clicking the menu Project > [ProjectName] Propertie s... and selecting the class containing the Main method that should be the entry point from the Startup object list box. 7.3 static Methods, static Variables and Class Math (Cont.)
The.NET Framework Class Library Predefined classes are grouped into categories of related classes called namespaces. Together, these namespaces are referred to as the.NET Framework Class Library.
22 Fig. 7.6 | Framework Class Library namespaces (a subset). (Part 1 of 2.) Some key Framework Class Library namespaces are described in Fig The.NET Framework Class Library (Cont.)
The.NET Framework Class Library (Cont.) Fig. 7.6 | Framework Class Library namespaces (a subset). (Part 2 of 2.)
The.NET Framework Class Library (Cont.) Good Programming Practice 7.2 The online.NET Framework documentation is easy to search and provides many details about each class. As you learn each class in this book, you should review the class in the online documentation for additional information.
25 Outline RandomIntegers.cs (1 of 2 ) Fig. 7.7 | Shifted and scaled random integers. (Part 1 of 2.) Rolling a Six-Sided Die Figure 7.7 shows two sample outputs of an application that simulates 20 rolls of a six-sided die and displays each roll’s value. Create the Random object randomNumbers to produce random values.
26 Outline Fig. 7.7 | Shifted and scaled random integers. (Part 2 of 2.) RandomIntegers.cs (2 of 2 ) Call Next with two arguments.
27 Outline Fig. 7.9 | Craps class simulates the dice game craps. (Part 1 of 4.) Craps.cs (1 of 4 ) The declaration of class Craps is shown in Fig A user-defined type called an enumeration declares a set of constants represented by identifiers, and is introduced by the keyword enum and a type name.
28 Outline Fig. 7.9 | Craps class simulates the dice game craps. (Part 2 of 4.) Craps.cs (2 of 4 ) Sums of the dice that would result in a win or loss on the first roll are declared in an enumeration. Must be initialized to 0 because it is not assigned a value in every branch of the switch statement. Initialization is not strictly necessary because it is assigned a value in every branch of the switch statement. Call method RollDice for the first roll of the game.
29 Outline Fig. 7.9 | Craps class simulates the dice game craps. (Part 3 of 4.) Craps.cs (3 of 4 ) Call method RollDice for subsequent rolls.
30 Outline Fig. 7.9 | Craps class simulates the dice game craps. (Part 4 of 4.) Craps.cs (4 of 4 ) Declare method RollDice to roll the dice and compute and display their sum.
Case Study: A Game of Chance (Introducing Enumerations) (Cont.) You can declare an enum’s underlying type to be byte, sbyte, short, ushort, int, uint, long or ulong by writing private enum MyEnum : typeName { Constant1, Constant2,... } – typeName represents one of the integral simple types. To compare a simple integral type value to the underlying value of an enumeration constant, you must use a cast operator.
Passing Arguments: Pass-by-Value vs. Pass-by-Reference Two ways to pass arguments to functions in many programming languages are pass-by-value and pass-by-reference. When an argument is passed by value (the default in C#), a copy of its value is made and passed to the called function. When an argument is passed by reference, the caller gives the method the ability to access and modify the caller’s original variable.
Passing Arguments: Pass-by-Value vs. Pass-by-Reference (Cont.) Performance Tip 7.1 Pass-by-reference is good for performance reasons, because it can eliminate the pass-by-value overhead of copying large amounts of data. Software Engineering Observation 7.5 Pass-by-reference can weaken security, because the called function can corrupt the caller’s data.
Passing Arguments: Pass-by-Value vs. Pass-by-Reference (Cont.) To pass an object by reference into a method, simply provide as an argument in the method call the variable that refers to the object. In the method body, the parameter will refer to the original object in memory, so the called method can access the original object directly. Passing a value-type variable to a method passes a copy of the value.
Passing Arguments: Pass-by-Value vs. Pass-by-Reference (Cont.) Passing a reference-type variable passes the method a copy of the actual reference that refers to the object. – The reference itself is passed by value, but the method can still use the reference it receives to modify the original object in memory. A return statement returns a copy of the value stored in a value-type variable or a copy of the reference stored in a reference-type variable. In effect, objects are always passed by reference.
Passing Arguments: Pass-by-Value vs. Pass-by-Reference (Cont.) Applying the ref keyword to a parameter declaration allows you to pass a variable to a method by reference The ref keyword is used for variables that already have been initialized in the calling method. Preceding a parameter with keyword out creates an output parameter. This indicates to the compiler that the argument will be passed by reference and that the called method will assign a value to it. A method can return multiple output parameters.
37 Outline ReferenceAndOutp utParameters.cs ( 1 of 4 ) Class ReferenceAndOutputParameters (Fig. 7.18) contains three methods that calculate the square of an integer. Fig | Reference, output and value parameters. (Part 1 of 4.)
38 Outline ReferenceAndOutp utParameters.cs ( 2 of 4 ) Fig | Reference, output and value parameters. (Part 2 of 4.) When you pass a variable to a method with a reference parameter, you must precede the argument with the same keyword ( ref or out ) that was used to declare the reference parameter.
39 Outline ReferenceAndOutp utParameters.cs ( 3 of 4 ) Fig | Reference, output and value parameters. (Part 3 of 4.) Modify caller’s x.
40 Outline ReferenceAndOutp utParameters.cs ( 4 of 4 ) Fig | Reference, output and value parameters. (Part 4 of 4.) Assign a value to caller’s uninitialized x. Doesn’t modify any caller variable.
Passing Arguments: Pass-by-Value vs. Pass-by-Reference (Cont.) When you pass a variable to a method with a reference parameter, you must precede the argument with the same keyword ( ref or out ) that was used to declare the reference parameter. Common Programming Error 7.12 The ref and out arguments in a method call must match the parameters specified in the method declaration; otherwise, a compilation error occurs.
Passing Arguments: Pass-by-Value vs. Pass-by-Reference (Cont.) Software Engineering Observation 7.6 By default, C# does not allow you to choose whether to pass each argument by value or by reference. Value types are passed by value. Objects are not passed to methods; rather, references to objects are passed to methods. The references themselves are passed by value. When a method receives a reference to an object, the method can manipulate the object directly, but the reference value cannot be changed to refer to a new object.
43 Outline ReferenceAnd OutputParamters Test.cs Class ReferenceAndOutputParametersTest tests the ReferenceAndOutputParameters class. Fig | Application to test class ReferenceAndOutputParameters.
foreach Statement The foreach statement iterates through the elements of an entire array or collection. The syntax of a foreach statement is: foreach ( type identifier in arrayName ) statement – type and identifier are the type and name (e.g., int number ) of the iteration variable. – arrayName is the array through which to iterate. The type of the iteration variable must match the type of the elements in the array. The iteration variable represents successive values in the array on successive iterations of the foreach statement.
45 Outline ForEachTest.cs ( 1 of 2 ) Figure 8.12 uses the foreach statement to calculate the sum of the integers in an array of student grades. Fig | Using the foreach statement to total integers in an array. For each iteration, number represents the next int value in the array.
foreach Statement (Cont.) Implicitly Typed Local Variables C# provides a new feature — called implicitly typed local variables — that enables the compiler to infer a local variable ’ s type based on the type of the variable ’ s initializer. To distinguish such an initialization from a simple assignment statement, the var keyword is used in place of the variable ’ s type. The compiler assumes that floating-point number values are of type double. You can use local type inference with control variables in the header of a for or foreach statement. For example, the following for statement headers are equivalent: for ( int counter = 1; counter < 10; counter++ ) for ( var counter = 1; counter < 10; counter++ )
foreach Statement (Cont.) Similarly, if myArray is an array of int s, the following foreach statement headers are equivalent: foreach (int number in myArray) foreach (var number in myArray) The implicitly typed local-variable feature is one of several new Visual C# 2008 features that support Language Integrated Query (LINQ). Implicitly typed local variables can be also used to initialize arrays without explicitly giving their type. – There are no square brackets on the left side of the assignment operator. – new[] is used on the right to specify that the variable is an array.
Passing Arrays by Value and by Reference (Cont.) You can use keyword ref to pass a reference-type variable by reference, which allows the called method to modify the original variable in the caller and make that variable refer to a different object. This is a subtle capability, which, if misused, can lead to problems.
49 Outline ArrayReference Test.cs ( 1 of 5 ) The application in Fig demonstrates the subtle difference between passing a reference by value and passing a reference by reference with keyword ref. Fig | Passing an array reference by value and by reference. (Part 1 of 5.)
50 Outline Fig | Passing an array reference by value and by reference. (Part 2 of 5.) ArrayReference Test.cs ( 2 of 5 )
51 Outline Fig | Passing an array reference by value and by reference. (Part 3 of 5.) ArrayReference Test.cs ( 3 of 5 )
52 Outline This does not overwrite the caller’s reference firstDouble. Fig | Passing an array reference by value and by reference. (Part 4 of 5.) ArrayReference Test.cs ( 4 of 5 )
53 Outline This assignment modifies the caller’s secondDouble reference to reference a new array. Fig | Passing an array reference by value and by reference. (Part 5 of 5.) ArrayReference Test.cs ( 5 of 5 )
Passing Arrays by Value and by Reference (Cont.) Software Engineering Observation 8.1 When a method receives a reference-type parameter by value, a copy of the object’s reference is passed. This prevents a method from overwriting references passed to that method. In the vast majority of cases, protecting the caller’s reference from modification is the desired behavior. If you encounter a situation where you truly want the called procedure to modify the caller’s reference, pass the reference-type parameter using keyword ref —but, again, such situations are rare. Software Engineering Observation 8.2 In C#, objects (including arrays) are effectively passed by reference, because references to objects are passed to called methods. A called method receiving a reference to an object in a caller can interact with, and possibly change, the caller’s object.
55 Outline InitArray.cs ( 1 of 3 ) Two-Dimensional Array Example: Displaying Element Values Figure 8.19 demonstrates initializing rectangular and jagged arrays with array initializers and using nested for loops to traverse the arrays. Initialize a rectangular array using nested array initializers. Each row of a jagged array is created with its own array initializer. Fig | Initializing jagged and rectangular arrays. (Part 1 of 3.)
56 Outline Use the rectangular array’s GetLength method to obtain the length of each dimension for the loop- continuation condition. Fig | Initializing jagged and rectangular arrays. (Part 2 of 3.) InitArray.cs ( 2 of 3 )
57 Outline Using foreach statements allows the loop to determine the exact number of columns in each row. Fig | Initializing jagged and rectangular arrays. (Part 3 of 3.) InitArray.cs ( 3 of 3 )
58 Outline ParamArrayTest.cs ( 1 of 3 ) Variable-length argument lists allow you to create methods that receive an arbitrary number of arguments. The necessary params modifier can occur only in the last entry of the parameter list. Figure 8.22 demonstrates method Average, which receives a variable-length sequence of double s. Fig | Using variable-length argument lists. (Part 1 of 3.)
59 Outline Fig | Using variable-length argument lists. (Part 2 of 3.) ParamArrayTest.cs ( 2 of 3 ) The method body can manipulate the parameter numbers as an array of double s.
60 Outline Fig | Using variable-length argument lists. (Part 3 of 3.) ParamArrayTest.cs ( 3 of 3 ) Common Programming Error 8.5 The params modifier may be used only with the last parameter of the parameter list.