60
1 1 // Fig. 3.17: Welcome4.cs 2 // Displaying multiple lines of text with string formatting. 3 using System; 4 5 public class Welcome4 6 { 7 // Main method begins execution of C# application 8 public static void Main( string[] args ) 9 { 10 Console.WriteLine( "{0}\n{1}", "Welcome to", "C# Programming!" ); 11 } // end Main 12 } // end class Welcome4 Welcome to C# Programming! 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. 3.17 | 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

Console methods Write and WriteLine also have the capability to display formatted data

  • Upload
    pakuna

  • View
    33

  • Download
    0

Embed Size (px)

DESCRIPTION

3.5  Formatting Text with Console.Write and Console.WriteLine. Outline. Welcome4.cs. Console methods Write and WriteLine also have the capability to display formatted data. Figure 3.17 shows another way to use the WriteLine method. . - PowerPoint PPT Presentation

Citation preview

Page 1: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

1

1 // Fig. 3.17: Welcome4.cs 2 // Displaying multiple lines of text with string formatting. 3 using System; 4 5 public class Welcome4 6 { 7 // Main method begins execution of C# application 8 public static void Main( string[] args ) 9 { 10 Console.WriteLine( "{0}\n{1}", "Welcome to", "C# Programming!" ); 11 } // end Main 12 } // end class Welcome4

Welcome to C# Programming!

• 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. 3.17 | 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

Page 2: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

2

1 // Fig. 3.18: Addition.cs 2 // Displaying the sum of two numbers input from the keyboard. 3 using System; 4 5 public class Addition 6 { 7 // Main method begins execution of C# application 8 public static void Main( string[] args ) 9 { 10 int number1; // declare first number to add 11 int number2; // declare second number to add 12 int sum; // declare sum of number1 and number2 13 14 Console.Write( "Enter first integer: " ); // prompt user 15 // read first number from user 16 number1 = Convert.ToInt32( Console.ReadLine() ); 17

Outline

Addition.cs

(1 of 2 )

Fig. 3.18 | Displaying the sum of two numbers input fromthe 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.

Page 3: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

3

18 Console.Write( "Enter second integer: " ); // prompt user 19 // read second number from user 20 number2 = Convert.ToInt32( Console.ReadLine() ); 21 22 sum = number1 + number2; // add numbers 23 24 Console.WriteLine( "Sum is {0}", sum ); // display sum 25 } // end Main 26 } // end class Addition Enter first integer: 45 Enter second integer: 72 Sum is 117

Outline

Addition.cs

(2 of 2 )

Fig. 3.18 | Displaying the sum of two numbers input fromthe keyboard. (Part 2 of 2).

Page 4: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

4

1 // Fig. 4.7: GradeBook.cs 2 // GradeBook class that contains a courseName instance variable, 3 // and a property to get and set its value. 4 using System; 5 6 public class GradeBook 7 { 8 private string courseName; // course name for this GradeBook 9 10 // property to get and set the course name

• 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.

Page 5: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

5

11 public string CourseName 12 { 13 get 14 { 15 return courseName; 16 } // end get 17 set 18 { 19 courseName = value; 20 } // end set 21 } // end property CourseName 22 23 // display a welcome message to the GradeBook user 24 public void DisplayMessage() 25 { 26 // use property CourseName to get the 27 // name of the course that this GradeBook represents 28 Console.WriteLine( "Welcome to the grade book for\n{0}!", 29 CourseName ); // display property CourseName 30 } // end method DisplayMessage 31 } // end class GradeBook

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.

Page 6: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

6

1 // Fig. 4.8: GradeBookTest.cs 2 // Create and manipulate a GradeBook object. 3 using System; 4 5 public class GradeBookTest 6 { 7 // Main method begins program execution 8 public static void Main( string[] args ) 9 { 10 // create a GradeBook object and assign it to myGradeBook 11 GradeBook myGradeBook = new GradeBook(); 12 13 // display initial value of CourseName 14 Console.WriteLine( "Initial course name is: '{0}'\n", 15 myGradeBook.CourseName ); 16

• 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.

Page 7: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

7

17 // prompt for and read course name 18 Console.WriteLine( "Please enter the course name:" ); 19 myGradeBook.CourseName = Console.ReadLine(); // set CourseName 20 Console.WriteLine(); // output a blank line 21 22 // display welcome message after specifying course name 23 myGradeBook.DisplayMessage(); 24 } // end Main 25 } // end class GradeBookTest Initial course name is: '' Please enter the course name: CS101 Introduction to C# Programming Welcome to the grade book for CS101 Introduction to C# Programming!

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.

Page 8: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

8

1 // Fig. 4.10: GradeBook.cs 2 // GradeBook class with an auto-implemented property. 3 using System; 4 5 public class GradeBook 6 { 7 // auto-implemented property CourseName implicitly creates 8 // an instance variable for this GradeBook's course name 9 public string CourseName { get; set; } 10 11 // display a welcome message to the GradeBook user 12 public void DisplayMessage() 13 { 14 // use auto-implemented property CourseName to get the 15 // name of the course that this GradeBook represents 16 Console.WriteLine( "Welcome to the grade book for\n{0}!", 17 CourseName ); // display auto-implemented property CourseName 18 } // end method DisplayMessage 19 } // end class GradeBook

• Figure 4.10 redefines class GradeBook with an auto-implemented CourseName property.

Outline

GradeBook.cs

Fig. 4.10 | GradeBook class with an auto-implemented property.

Declaring the auto-implemented property.

Implicitly obtaining the property’s value.

Page 9: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

9

1 // Fig. 4.8: GradeBookTest.cs 2 // Create and manipulate a GradeBook object. 3 using System; 4 5 public class GradeBookTest 6 { 7 // Main method begins program execution 8 public static void Main( string[] args ) 9 { 10 // create a GradeBook object and assign it to myGradeBook 11 GradeBook myGradeBook = new GradeBook(); 12 13 // display initial value of CourseName 14 Console.WriteLine( "Initial course name is: '{0}'\n", 15 myGradeBook.CourseName ); 16

• 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.

Page 10: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

10

17 // prompt for and read course name 18 Console.WriteLine( "Please enter the course name:" ); 19 myGradeBook.CourseName = Console.ReadLine(); // set CourseName 20 Console.WriteLine(); // output a blank line 21 22 // display welcome message after specifying course name 23 myGradeBook.DisplayMessage(); 24 } // end Main 25 } // end class GradeBookTest Initial course name is: '' Please enter the course name: CS101 Introduction to C# Programming Welcome to the grade book for CS101 Introduction to C# Programming!

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.

Page 11: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

11

1 // Fig. 4.17: Account.cs 2 // Account class with a constructor to 3 // initialize instance variable balance. 4 5 public class Account 6 { 7 private decimal balance; // instance variable that stores the balance 8 9 // constructor 10 public Account( decimal initialBalance ) 11 { 12 Balance = initialBalance; // set balance using property 13 } // end Account constructor 14 15 // credit (add) an amount to the account 16 public void Credit( decimal amount ) 17 { 18 Balance = Balance + amount; // add amount to balance 19 } // end method Credit

• A class named Account (Fig. 4.17) maintains the balance of a bank account.

Outline

Account.cs

(1 of 2 )

Fig. 4.17 | Account class with a constructor to initialize instancevariable 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.

Page 12: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

12

20 21 // a property to get and set the account balance 22 public decimal Balance 23 { 24 get 25 { 26 return balance; 27 } // end get 28 set 29 { 30 // validate that value is greater than or equal to 0; 31 // if it is not, balance is left unchanged 32 if ( value >= 0 ) 33 balance = value; 34 } // end set 35 } // end property Balance 36 } // end class Account

Outline

Account.cs

(2 of 2 )

Fig. 4.17 | Account class with a constructor to initialize instancevariable 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.

Page 13: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

13

1 // Fig. 4.18: AccountTest.cs 2 // Create and manipulate Account objects. 3 using System; 4 5 public class AccountTest 6 { 7 // Main method begins execution of C# application 8 public static void Main( string[] args ) 9 { 10 Account account1 = new Account( 50.00M ); // create Account object 11 Account account2 = new Account( -7.53M ); // create Account object 12 13 // display initial balance of each object using a property 14 Console.WriteLine( "account1 balance: {0:C}", 15 account1.Balance ); // display Balance property 16 Console.WriteLine( "account2 balance: {0:C}\n", 17 account2.Balance ); // display Balance property 18

• AccountTest (Fig. 4.18) creates two Account objects and initializes them with 50.00M and -7.53M (decimal literals).

Outline

AccountTest.cs

(1 of 3 )

Fig. 4.18 | 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.

Page 14: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

14

19 decimal depositAmount; // deposit amount read from user 20 21 // prompt and obtain user input 22 Console.Write( "Enter deposit amount for account1: " ); 23 depositAmount = Convert.ToDecimal( Console.ReadLine() ); 24 Console.WriteLine( "adding {0:C} to account1 balance\n", 25 depositAmount ); 26 account1.Credit( depositAmount ); // add to account1 balance 27 28 // display balances 29 Console.WriteLine( "account1 balance: {0:C}", 30 account1.Balance ); 31 Console.WriteLine( "account2 balance: {0:C}\n", 32 account2.Balance ); 33 34 // prompt and obtain user input 35 Console.Write( "Enter deposit amount for account2: " ); 36 depositAmount = Convert.ToDecimal( Console.ReadLine() );

Outline

AccountTest.cs

(2 of 3 )

Fig. 4.18 | 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.

Page 15: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

15

37 Console.WriteLine( "adding {0:C} to account2 balance\n", 38 depositAmount ); 39 account2.Credit( depositAmount ); // add to account2 balance 40 41 // display balances 42 Console.WriteLine( "account1 balance: {0:C}", account1.Balance ); 43 Console.WriteLine( "account2 balance: {0:C}", account2.Balance ); 44 } // end Main 45 } // end class AccountTest account1 balance: $50.00 account2 balance: $0.00 Enter deposit amount for account1: 49.99 adding $49.99 to account1 balance account1 balance: $99.99 account2 balance: $0.00 Enter deposit amount for account2: 123.21 adding $123.21 to account2 balance account1 balance: $99.99 account2 balance: $123.21

Outline

AccountTest.cs

(3 of 3 )

Fig. 4.18 | Create and manipulate an Account object. (Part 3 of 3).

Outputting the balances of both Accounts.

Page 16: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

16

4.11 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.

Page 17: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

17

Format specifier Description

­ C­or­c­ Formats the string as currency.

­ D or d­ Formats the string as a decimal.

­ N or n­ Formats the string with a thousands separator and two decimal places.

­ E or e­ Formats the number using scientific notation.

­ F or f­ Formats the string with a fixed number of decimal places.

­ G or g­ Default setting. Formats the number with decimal places or using scientific notation, depending on context.

­ X or x­ Formats the string as hexadecimal.

Fig. 4.19 | string format specifiers.

4.11 Floating-Point Numbers and Type decimal (Cont.)

Page 18: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

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 strings 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.)

Page 19: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

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.)

Page 20: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

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] Properties... 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.)

Page 21: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

21

7.8 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.

Page 22: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

22

Fig. 7.6 | Framework Class Library namespaces (a subset). (Part 1 of 2.)

Namespace Description

­ System.Windows.Forms­ Contains the classes required to create and manipulate GUIs.

­ System.Windows.Controls­ System.Windows.Input­­ System.Windows.Media­­ System.Windows.Shapes

Contain the classes of the Windows Presentation Foundation for GUIs, 2-D and 3-D graphics, multimedia and animation.

­ System.Linq­

Contains the classes that support Language Integrated Query (LINQ).

­ System.Data­­ System.Data.Linq­

Contain the classes for manipulating data in databases (i.e., organized collections of data), including support for LINQ to SQL.

• Some key Framework Class Library namespaces are described in Fig. 7.6.

7.8 The .NET Framework Class Library (Cont.)

Page 23: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

23

Namespace Description

­ System.IO­ Contains classes that enable programs to input and output data.

­ System.Web­ Contains classes used for creating and maintaining web applications, which are accessible over the Internet.

­ System.Xml.Linq­

Contains the classes that support Language Integrated Query (LINQ) for XML documents.

­ System.Xml­ Contains classes for creating and manipulating XML data. Data can be read from or written to XML files.

­ System.Collections­­ System.Collections.Generic­

Contain classes that define data structures for maintaining collections of data.

­ System.Text­ Contains classes that enable programs to manipulate characters and strings.

7.8 The .NET Framework Class Library (Cont.)

Fig. 7.6 | Framework Class Library namespaces (a subset). (Part 2 of 2.)

Page 24: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

24

7.8 The .NET Framework Class Library (Cont.)

Good Programming Practice 7.2The 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.

Page 25: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

25

1 // Fig. 7.7: RandomIntegers.cs 2 // Shifted and scaled random integers. 3 using System; 4 5 public class RandomIntegers 6 { 7 public static void Main( string[] args ) 8 { 9 Random randomNumbers = new Random(); // random-number generator 10 int face; // stores each random integer generated 11 12 // loop 20 times 13 for ( int counter = 1; counter <= 20; counter++ ) 14 { 15 // pick random integer from 1 to 6

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-sideddie and displays each roll’s value.

Create the Random object randomNumbers to produce random values.

Page 26: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

26

16 face = randomNumbers.Next( 1, 7 ); 17 18 Console.Write( "{0} ", face ); // display generated value 19 20 // if counter is divisible by 5, start a new line of output 21 if ( counter % 5 == 0 ) 22 Console.WriteLine(); 23 } // end for 24 } // end Main 25 } // end class RandomIntegers 3 3 3 1 1 2 1 2 4 2 2 3 6 2 5 3 4 6 6 1 6 2 5 1 3 5 2 1 6 5 4 1 6 1 3 3 1 4 3 4

Outline

Fig. 7.7 | Shifted and scaled random integers. (Part 2 of 2.)

RandomIntegers.cs

(2 of 2 )

Call Next with two arguments.

Page 27: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

27

1 // Fig. 7.9: Craps.cs 2 // Craps class simulates the dice game craps. 3 using System; 4 5 public class Craps 6 { 7 // create random-number generator for use in method RollDice 8 private Random randomNumbers = new Random(); 9 10 // enumeration with constants that represent the game status 11 private enum Status { CONTINUE, WON, LOST } 12 13 // enumeration with constants that represent common rolls of the dice

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. 7.9.

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.

Page 28: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

28

14 private enum DiceNames 15 { 16 SNAKE_EYES = 2, 17 TREY = 3, 18 SEVEN = 7, 19 YO_LEVEN = 11, 20 BOX_CARS = 12 21 } 22 23 // plays one game of craps 24 public void Play() 25 { 26 // gameStatus can contain CONTINUE, WON or LOST 27 Status gameStatus = Status.CONTINUE; 28 int myPoint = 0; // point if no win or loss on first roll 29 30 int sumOfDice = RollDice(); // first roll of the dice 31 32 // determine game status and point based on first roll 33 switch ( ( DiceNames ) sumOfDice ) 34 { 35 case DiceNames.SEVEN: // win with 7 on first roll 36 case DiceNames.YO_LEVEN: // win with 11 on first roll 37 gameStatus = Status.WON;

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.

Page 29: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

29

38 break; 39 case DiceNames.SNAKE_EYES: // lose with 2 on first roll 40 case DiceNames.TREY: // lose with 3 on first roll 41 case DiceNames.BOX_CARS: // lose with 12 on first roll 42 gameStatus = Status.LOST; 43 break; 44 default: // did not win or lose, so remember point 45 gameStatus = Status.CONTINUE; // game is not over 46 myPoint = sumOfDice; // remember the point 47 Console.WriteLine( "Point is {0}", myPoint ); 48 break; 49 } // end switch 50 51 // while game is not complete 52 while ( gameStatus == Status.CONTINUE ) // game not WON or LOST 53 { 54 sumOfDice = RollDice(); // roll dice again 55 56 // determine game status 57 if ( sumOfDice == myPoint ) // win by making point 58 gameStatus = Status.WON; 59 else 60 // lose by rolling 7 before point 61 if ( sumOfDice == ( int ) DiceNames.SEVEN ) 62 gameStatus = Status.LOST; 63 } // end while

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.

Page 30: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

30

64 65 // display won or lost message 66 if ( gameStatus == Status.WON ) 67 Console.WriteLine( "Player wins" ); 68 else 69 Console.WriteLine( "Player loses" ); 70 } // end method Play 71 72 // roll dice, calculate sum and display results 73 public int RollDice() 74 { 75 // pick random die values 76 int die1 = randomNumbers.Next( 1, 7 ); // first die roll 77 int die2 = randomNumbers.Next( 1, 7 ); // second die roll 78 79 int sum = die1 + die2; // sum of die values 80 81 // display results of this roll 82 Console.WriteLine( "Player rolled {0} + {1} = {2}", 83 die1, die2, sum ); 84 return sum; // return sum of dice 85 } // end method RollDice 86 } // end class Craps

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.

Page 31: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

31

7.10 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.

Page 32: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

32

7.14 Passing Arguments: Pass-by-Value vs. Pass-by-Reference

• Two ways to pass arguments to functions in many programming languages are pass-by-value andpass-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.

Page 33: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

33

7.14 Passing Arguments: Pass-by-Value vs. Pass-by-Reference (Cont.)

Performance Tip 7.1Pass-by-reference is good for performance reasons, becauseit can eliminate the pass-by-value overhead of copying large amounts of data.

Software Engineering Observation 7.5Pass-by-reference can weaken security, because the called function can corrupt the caller’s data.

Page 34: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

34

7.14 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.

Page 35: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

35

7.14 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.

Page 36: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

36

7.14 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.

Page 37: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

37

1 // Fig. 7.18: ReferenceAndOutputParameters.cs 2 // Reference, output and value parameters. 3 using System; 4 5 class ReferenceAndOutputParameters 6 { 7 // call methods with reference, output and value parameters 8 public void DemonstrateReferenceAndOutputParameters() 9 { 10 int y = 5; // initialize y to 5

Outline

ReferenceAndOutputParameters.cs

( 1 of 4 )

• Class ReferenceAndOutputParameters (Fig. 7.18) contains three methods that calculate the square of an integer.

Fig. 7.18 | Reference, output and value parameters. (Part 1 of 4.)

Page 38: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

38

11 int z; // declares z, but does not initialize it 12 13 // display original values of y and z 14 Console.WriteLine( "Original value of y: {0}", y ); 15 Console.WriteLine( "Original value of z: uninitialized\n" ); 16 17 // pass y and z by reference 18 SquareRef( ref y ); // must use keyword ref 19 SquareOut( out z ); // must use keyword out 20 21 // display values of y and z after they are modified by 22 // methods SquareRef and SquareOut, respectively 23 Console.WriteLine( "Value of y after SquareRef: {0}", y );

Outline

ReferenceAndOutputParameters.cs

( 2 of 4 )

Fig. 7.18 | 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.

Page 39: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

39

24 Console.WriteLine( "Value of z after SquareOut: {0}\n", z ); 25 26 // pass y and z by value 27 Square( y ); 28 Square( z ); 29 30 // display values of y and z after they are passed to method Square 31 // to demonstrate that arguments passed by value are not modified 32 Console.WriteLine( "Value of y after Square: {0}", y ); 33 Console.WriteLine( "Value of z after Square: {0}", z ); 34 } // end method DemonstrateReferenceAndOutputParameters 35 36 // uses reference parameter x to modify caller's variable 37 void SquareRef( ref int x ) 38 { 39 x = x * x; // squares value of caller's variable 40 } // end method SquareRef 41

Outline

ReferenceAndOutputParameters.cs

( 3 of 4 )

Fig. 7.18 | Reference, output and value parameters. (Part 3 of 4.)

Modify caller’s x.

Page 40: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

40

41 42 // uses output parameter x to assign a value 43 // to an uninitialized variable 44 void SquareOut( out int x ) 45 { 46 x = 6; // assigns a value to caller's variable 47 x = x * x; // squares value of caller's variable 48 } // end method SquareOut 49 50 // parameter x receives a copy of the value passed as an argument, 51 // so this method cannot modify the caller's variable 52 void Square( int x ) 53 { 54 x = x * x; 55 } // end method Square 56 } // end class ReferenceAndOutputParameters

Outline

ReferenceAndOutputParameters.cs

( 4 of 4 )

Fig. 7.18 | Reference, output and value parameters. (Part 4 of 4.)

Assign a value to caller’s uninitialized x.

Doesn’t modify any caller variable.

Page 41: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

41

7.14 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.12The ref and out arguments in a method call must match the parameters specified in the method declaration; otherwise, a compilation error occurs.

Page 42: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

42

7.14 Passing Arguments: Pass-by-Value vs. Pass-by-Reference (Cont.)

Software Engineering Observation 7.6By 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.

Page 43: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

43

1 // Fig. 7.19: ReferenceAndOutputParamtersTest.cs 2 // Application to test class ReferenceAndOutputParameters. 3 class ReferenceAndOutputParamtersTest 4 { 5 public static void Main( string[] args ) 6 { 7 ReferenceAndOutputParameters test = 8 new ReferenceAndOutputParameters(); 9 test.DemonstrateReferenceAndOutputParameters(); 10 } // end Main 11 } // end class ReferenceAndOutputParamtersTest Original value of y: 5 Original value of z: uninitialized Value of y after SquareRef: 25 Value of z after SquareOut: 36 Value of y after Square: 25 Value of z after Square: 36

Outline

ReferenceAndOutputParamtersTest.cs

• Class ReferenceAndOutputParametersTest tests the ReferenceAndOutputParameters class.

Fig. 7.19 | Application to test class ReferenceAndOutputParameters.

Page 44: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

44

8.6 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.

Page 45: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

45

1 // Fig. 8.12: ForEachTest.cs 2 // Using the foreach statement to total integers in an array. 3 using System; 4 5 public class ForEachTest 6 { 7 public static void Main( string[] args ) 8 { 9 int[] array = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 }; 10 int total = 0; 11 12 // add each element's value to total 13 foreach ( int number in array ) 14 total += number; 15 16 Console.WriteLine( "Total of array elements: {0}", total ); 17 } // end Main 18 } // end class ForEachTest Total of array elements: 849

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. 8.12 | Using the foreach statement to total integers in an array.

For each iteration, number­represents the next int value in the array.

Page 46: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

46

8.6 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++­)

Page 47: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

47

8.6 foreach Statement (Cont.) • Similarly, if myArray is an array of ints, 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.

Page 48: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

48

8.8 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.

Page 49: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

49

1 // Fig. 8.14: ArrayReferenceTest.cs 2 // Testing the effects of passing array references 3 // by value and by reference. 4 using System; 5 6 public class ArrayReferenceTest 7 { 8 public static void Main( string[] args ) 9 { 10 // create and initialize firstArray 11 int[] firstArray = { 1, 2, 3 }; 12 13 // copy the reference in variable firstArray 14 int[] firstArrayCopy = firstArray; 15 16 Console.WriteLine( 17 "Test passing firstArray reference by value" ); 18

Outline

ArrayReferenceTest.cs

( 1 of 5 )

• The application in Fig. 8.14 demonstrates the subtle difference between passing a reference by value and passing a reference by reference with keyword ref.

Fig. 8.14 | Passing an array reference by value and by reference. (Part 1 of 5.)

Page 50: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

50

19 Console.Write( "\nContents of firstArray " + 20 "before calling FirstDouble:\n\t" ); 21 22 // display contents of firstArray 23 for ( int i = 0; i < firstArray.Length; i++ ) 24 Console.Write( "{0} ", firstArray[ i ] ); 25 26 // pass variable firstArray by value to FirstDouble 27 FirstDouble( firstArray ); 28 29 Console.Write( "\n\nContents of firstArray after " + 30 "calling FirstDouble\n\t" ); 31 32 // display contents of firstArray 33 for ( int i = 0; i < firstArray.Length; i++ ) 34 Console.Write( "{0} ", firstArray[ i ] ); 35 36 // test whether reference was changed by FirstDouble 37 if ( firstArray == firstArrayCopy ) 38 Console.WriteLine( 39 "\n\nThe references refer to the same array" ); 40 else 41 Console.WriteLine( 42 "\n\nThe references refer to different arrays" ); 43

Outline

Fig. 8.14 | Passing an array reference by value and by reference. (Part 2 of 5.)

ArrayReferenceTest.cs

( 2 of 5 )

Page 51: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

51

44 // create and initialize secondArray 45 int[] secondArray = { 1, 2, 3 }; 46 47 // copy the reference in variable secondArray 48 int[] secondArrayCopy = secondArray; 49 50 Console.WriteLine( "\nTest passing secondArray " + 51 "reference by reference" ); 52 53 Console.Write( "\nContents of secondArray " + 54 "before calling SecondDouble:\n\t" ); 55 56 // display contents of secondArray before method call 57 for ( int i = 0; i < secondArray.Length; i++ ) 58 Console.Write( "{0} ", secondArray[ i ] ); 59 60 // pass variable secondArray by reference to SecondDouble 61 SecondDouble( ref secondArray ); 62 63 Console.Write( "\n\nContents of secondArray " + 64 "after calling SecondDouble:\n\t" ); 65 66 // display contents of secondArray after method call 67 for ( int i = 0; i < secondArray.Length; i++ ) 68 Console.Write( "{0} ", secondArray[ i ] );

Outline

Fig. 8.14 | Passing an array reference by value and by reference. (Part 3 of 5.)

ArrayReferenceTest.cs

( 3 of 5 )

Page 52: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

52

69 70 // test whether reference was changed by SecondDouble 71 if ( secondArray == secondArrayCopy ) 72 Console.WriteLine( 73 "\n\nThe references refer to the same array" ); 74 else 75 Console.WriteLine( 76 "\n\nThe references refer to different arrays" ); 77 } // end Main 78 79 // modify elements of array and attempt to modify reference 80 public static void FirstDouble( int[] array ) 81 { 82 // double each element's value 83 for ( int i = 0; i < array.Length; i++ ) 84 array[ i ] *= 2; 85 86 // create new object and assign its reference to array 87 array = new int[] { 11, 12, 13 }; 88 } // end method FirstDouble 89 90 // modify elements of array and change reference array 91 // to refer to a new array

Outline

This does not overwrite the caller’s reference firstDouble.

Fig. 8.14 | Passing an array reference by value and by reference. (Part 4 of 5.)

ArrayReferenceTest.cs

( 4 of 5 )

Page 53: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

53

92 public static void SecondDouble( ref int[] array ) 93 { 94 // double each element's value 95 for ( int i = 0; i < array.Length; i++ ) 96 array[ i ] *= 2; 97 98 // create new object and assign its reference to array 99 array = new int[] { 11, 12, 13 }; 100 } // end method SecondDouble 101 } // end class ArrayReferenceTest Test passing firstArray reference by value Contents of firstArray before calling FirstDouble: 1 2 3 Contents of firstArray after calling FirstDouble 2 4 6 The references refer to the same array Test passing secondArray reference by reference Contents of secondArray before calling SecondDouble: 1 2 3 Contents of secondArray after calling SecondDouble: 11 12 13 The references refer to different arrays

Outline

This assignment modifies the caller’s secondDouble reference to reference a new array.

Fig. 8.14 | Passing an array reference by value and byreference. (Part 5 of 5.)

ArrayReferenceTest.cs

( 5 of 5 )

Page 54: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

54

8.8 Passing Arrays by Value and by Reference (Cont.)

Software Engineering Observation 8.1When 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.2In 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.

Page 55: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

55

1 // Fig. 8.19: InitArray.cs 2 // Initializing rectangular and jagged arrays. 3 using System; 4 5 public class InitArray 6 { 7 // create and output rectangular and jagged arrays 8 public static void Main( string[] args ) 9 { 10 // with rectangular arrays, 11 // every column must be the same length. 12 int[ , ] rectangular = { { 1, 2, 3 }, { 4, 5, 6 } }; 13 14 // with jagged arrays, 15 // we need to use "new int[]" for every row, 16 // but every column does not need to be the same length. 17 int[][] jagged = { new int[] { 1, 2 }, 18 new int[] { 3 }, 19 new int[] { 4, 5, 6 } };

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. 8.19 | Initializing jagged and rectangular arrays. (Part 1 of 3.)

Page 56: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

56

20 21 OutputArray( rectangular ); // displays array rectangular by row 22 Console.WriteLine(); // output a blank line 23 OutputArray( jagged ); // displays array jagged by row 24 } // end Main 25 26 // output rows and columns of a rectangular array 27 public static void OutputArray( int[ , ] array ) 28 { 29 Console.WriteLine( "Values in the rectangular array by row are" ); 30 31 // loop through array's rows 32 for ( int row = 0; row < array.GetLength( 0 ); row++ ) 33 { 34 // loop through columns of current row 35 for ( int column = 0; column < array.GetLength( 1 ); column++ ) 36 Console.Write( "{0} ", array[ row, column ] ); 37 38 Console.WriteLine(); // start new line of output 39 } // end outer for 40 } // end method OutputArray 41

Outline

Use the rectangular array’s GetLength method to obtain the length of each dimension for the loop-continuation condition.

Fig. 8.19 | Initializing jagged and rectangular arrays. (Part 2 of 3.)

InitArray.cs

( 2 of 3 )

Page 57: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

57

42 // output rows and columns of a jagged array 43 public static void OutputArray( int[][] array ) 44 { 45 Console.WriteLine( "Values in the jagged array by row are" ); 46 47 // loop through each row 48 foreach ( var row in array ) 49 { 50 // loop through each element in current row 51 foreach ( var element in row ) 52 Console.Write( "{0} ", element ); 53 54 Console.WriteLine(); // start new line of output 55 } // end outer foreach 56 } // end method OutputArray 57 } // end class InitArray Values in the rectangular array by row are 1 2 3 4 5 6 Values in the jagged array by row are 1 2 3 4 5 6

Outline

Using foreach statements allows the loop to determine the exact number of columns in each row.

Fig. 8.19 | Initializing jagged and rectangular arrays. (Part 3 of 3.)

InitArray.cs

( 3 of 3 )

Page 58: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

58

1 // Fig. 8.22: ParamArrayTest.cs 2 // Using variable-length argument lists. 3 using System; 4 5 public class ParamArrayTest 6 { 7 // calculate average 8 public static double Average( params double[] numbers ) 9 { 10 double total = 0.0; // initialize total 11

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 doubles.

Fig. 8.22 | Using variable-length argument lists. (Part 1 of 3.)

Page 59: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

59

12 // calculate total using the foreach statement 13 foreach ( double d in numbers ) 14 total += d; 15 16 return total / numbers.Length; 17 } // end method Average 18 19 public static void Main( string[] args ) 20 { 21 double d1 = 10.0; 22 double d2 = 20.0; 23 double d3 = 30.0; 24 double d4 = 40.0; 25 26 Console.WriteLine( 27 "d1 = {0:F1}\nd2 = {1:F1}\nd3 = {2:F1}\nd4 = {3:F1}\n", 28 d1, d2, d3, d4 ); 29

Outline

Fig. 8.22 | 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 doubles.

Page 60: Console  methods  Write  and  WriteLine  also have the capability to display formatted data

60

30 Console.WriteLine( "Average of d1 and d2 is {0:F1}", 31 Average( d1, d2 ) ); 32 Console.WriteLine( "Average of d1, d2 and d3 is {0:F1}", 33 Average( d1, d2, d3 ) ); 34 Console.WriteLine( "Average of d1, d2, d3 and d4 is {0:F1}", 35 Average( d1, d2, d3, d4 ) ); 36 } // end Main 37 } // end class ParamArrayTest d1 = 10.0 d2 = 20.0 d3 = 30.0 d4 = 40.0 Average of d1 and d2 is 15.0 Average of d1, d2 and d3 is 20.0 Average of d1, d2, d3 and d4 is 25.0

Outline

Fig. 8.22 | Using variable-length argument lists. (Part 3 of 3.)

ParamArrayTest.cs

( 3 of 3 )

Common Programming Error 8.5The params modifier may be used only with the last parameter of the parameter list.