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
60
Embed
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.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
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
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).
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.
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.
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.
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.
8
1 // Fig. 4.10: GradeBook.cs
2 // GradeBook class with an auto-implemented property.
• 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.
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.
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.
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
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.
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.
17
Format specifier Description
Corc 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.)
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.)
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] 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.)
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.
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.
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.)
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.
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.
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
Fig. 7.7 | Shifted and scaled random integers. (Part 2 of 2.)
RandomIntegers.cs
(2 of 2 )
Call Next with two arguments.
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.
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.
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.
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
– 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.
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.
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.
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.
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.
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.
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.)
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.
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.
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.
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.
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.
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.
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.
45
1 // Fig. 8.12: ForEachTest.cs
2 // Using the foreach statement to total integers in an array.
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, numberrepresents the next int value in the array.
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(intcounter=1;counter<10; counter++)for(varcounter=1;counter<10;counter++)
47
8.6 foreach Statement (Cont.) • Similarly, if myArray is an array of ints, the following foreach
statement headers are equivalent:foreach(intnumberinmyArray)foreach(varnumberinmyArray)
• 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.
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.
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.)
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.)
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 )
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 )
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 )
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.
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
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.
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.