Methods and Behaviors: C# Programming

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 60

3 Methods and

Behaviors

C# Programming: From Problem Analysis to Program Design


2nd Edition

C# Programming: From Problem Analysis to Program Design 1


Anatomy of a Method
• Methods defined inside classes
• Group program statements
– Based on functionality
– Called one or more times
• All programs consist of at least one method
– Main( )
• User-defined method

C# Programming: From Problem Analysis to Program Design 2


/* SquareExample.cs Author: Doyle */
using System;
namespace Square
{
public class SquareExample
{
public static void Main( ) Required method
{
int aValue = 768;
int result;
result = aValue * aValue;
Console.WriteLine(“{0} squared is {1}”,
aValue, result);
Console.Read( );
}
}
}
C# Programming: From Problem Analysis to Program Design 3
Anatomy of a Method (continued)

Figure 4-1 Method components


C# Programming: From Problem Analysis to Program Design 4
Modifiers
• Appear in method headings
• Appear in the declaration heading for classes and
other class members
• Indicate how it can be accessed
• Types of modifiers
– Static
– Access

C# Programming: From Problem Analysis to Program Design 5


Static Modifier
• Indicates member belongs to the type itself rather
than to a specific object of a class
• Main( ) must include static in heading
• Members of the Math class are static
– public static double Pow(double, double)
• Methods that use the static modifier are called
class methods
– Instance methods require an object
C# Programming: From Problem Analysis to Program Design 6
Access Modifiers
• public

• protected

• internal

• protected internal

• private
C# Programming: From Problem Analysis to Program Design 7
Level of Accessibility

C# Programming: From Problem Analysis to Program Design 8


Return Type
• Indicates what type of value is returned when the
method is completed
• Always listed immediately before method name
• void
– No value being returned
• return statement
– Required for all non-void methods
– Compatible value
C# Programming: From Problem Analysis to Program Design 9
Return Return Type (continued)
type
public static double CalculateMilesPerGallon
(int milesTraveled, double gallonsUsed)
{
return milesTraveled / gallonsUsed;
}

Compatible value
(double) returned

C# Programming: From Problem Analysis to Program Design 10


Method Names
• Follow the rules for creating an identifier
– Pascal case style
– Action verb or prepositional phrase
• Examples
– CalculateSalesTax( )
– AssignSectionNumber( )
– DisplayResults( )
– InputAge( )
– ConvertInputValue( )
C# Programming: From Problem Analysis to Program Design 11
Parameters
• Supply unique data to method
• Appear inside parentheses
– Include data type and an identifier
• In method body, reference values using identifier
name
– Parameter refers to items appearing in the heading
– Argument for items appearing in the call
• Formal parameters
• Actual arguments
C# Programming: From Problem Analysis to Program Design 12
Parameters (continued)
public static double CalculateMilesPerGallon
(int milesTraveled, double gallonsUsed)
{
return milesTraveled / gallonsUsed; Two formal
} parameters

• Call to method inside Main( ) method


Console.WriteLine(“Miles per gallon = {0:N2}”,
CalculateMilesPerGallon(289, 12.2));

Actual
C# Programming: From Problem Analysis to Program Design arguments 13
Parameters (continued)
• Like return types, parameters are optional
– Keyword void not required (inside parentheses) –
when there are no parameters
public void DisplayMessage( )
{
Console.Write(”This is “);
Console.Write(”an example of a method ”);
Console.WriteLine(“body. ”);
return; // no value is returned
}
C# Programming: From Problem Analysis to Program Design 14
Method Body
• Enclosed in curly braces
• Include statements ending in semicolons
– Declare variables
– Do arithmetic
– Call other methods

• Value-returning methods must include return


statement
C# Programming: From Problem Analysis to Program Design 15
Calling Class Methods
• Invoke a method
• Call to method that returns no value
[qualifier].MethodName(argumentList);
• Qualifier
– Square brackets indicate optional
– class or object name
• Call to method does not include data type
• Use Intellisense
C# Programming: From Problem Analysis to Program Design 16
Predefined Methods
• Extensive class library
• Console class
– Overloaded methods
– Write( )
– WriteLine( )
– Read( )
• Not overloaded
• Returns an integer
C# Programming: From Problem Analysis to Program Design 17
Intellisense
After
After typing
typing the
the dot,
dot, list
list
of
of members
members pops
pops up
up

Method signature(s)
Method signature(s)
and description
and description

3-D fuchsia colored box —


methods
Figure 4-2 Console class members aqua colored box — fields (not
shown)
C# Programming: From Problem Analysis to Program Design 18
Intellisense Display
string argument
expected

string
parameter

18 different Write( )
methods

Figure 4-3 IntelliSense display


C# Programming: From Problem Analysis to Program Design 19
Intellisense Display (continued)

Figure 4-4 Console.Read ( ) signature

Figure 4-5 Console.ReadLine ( ) signature


C# Programming: From Problem Analysis to Program Design 20
Call Read( ) Methods
int aNumber;
Console.Write(“Enter a single character: ”);
aNumber = Console.Read( );
Console.WriteLine(“The value of the character entered: ”
+ aNumber);
Enter a single character: a
The value of the character entered: 97

C# Programming: From Problem Analysis to Program Design 21


Call Read( ) Methods (continued)
int aNumber;
Console.WriteLine(“The value of the character entered: “
+ (char) Console.Read( ));

Enter a single character: a


The value of the character entered: a

C# Programming: From Problem Analysis to Program Design 22


Call ReadLine( ) Methods
• More versatile than the Read( )
• Returns all characters up to the enter key
• Not overloaded
• Always returns a string
• String value must be parsed

C# Programming: From Problem Analysis to Program Design 23


Call Parse( )
• Predefined static method
• All numeric types have a Parse( ) method
– double.Parse(“string number”)
– int.Parse(“string number”)
– char.Parse(“string number”)
– bool.Parse(“string number”)
• Expects string argument
– Argument must be a number – string format
• Returns the number (or char or bool)
C# Programming: From Problem Analysis to Program Design 24
/* AgeIncrementer.cs Author: Doyle */
using System;
namespace AgeExample
{
public class AgeIncrementer
{
public static void Main( )
{
int age;
string aValue;
Console.Write(“Enter your age: “);
aValue = Console.ReadLine( );
age = int.Parse(aValue);
Console.WriteLine(“Your age next year”
+ “ will be {0}”, ++age);
Console.Read( );
} } }
C# Programming: From Problem Analysis to Program Design 25
/* SquareInputValue.cs Author: Doyle */
using System;
namespace Square
{
class SquareInputValue
{
static void Main( )
{
string inputStringValue;
double aValue, result;
Console.Write(“Enter a value to be squared: ”);
inputStringValue = Console.ReadLine( );
aValue = double.Parse(inputStringValue);
result = Math.Pow(aValue, 2);
Console.WriteLine(“{0} squared is {1}”, aValue, result);
}
}
C# Programming: From Problem Analysis to Program Design 26
}
Call Parse( ) (continued)
string sValue = “True”;
Console.WriteLine (bool.Parse(sValue)); // displays True
string strValue = “q”;
Console.WriteLine(char.Parse(strValue)); // displays q

C# Programming: From Problem Analysis to Program Design 27


Call Parse( ) with Incompatible
Value
• Console.WriteLine(char.Parse(sValue));
when sValue referenced “True”

Figure 4-6 System.FormatException run-time error


C# Programming: From Problem Analysis to Program Design 28
Convert Class
• More than one way to convert from one base type
to another
– System namespace — Convert class — static methods
– Convert.ToDouble( )
– Convert.ToDecimal( )
– Convert.ToInt32( )
– Convert.ToBoolean( )
– Convert.ToChar( )
int newValue = Convert.ToInt32(stringValue);

C# Programming: From Problem Analysis to Program Design 29


C# Programming: From Problem Analysis to Program Design 30
C# Programming: From Problem Analysis to Program Design 31
C# Programming: From Problem Analysis to Program Design 32
Math( ) Class
double aValue = 78.926; Each call
double result1, returns a value
result2;
result1 = Math.Floor(aValue); // result1 = 78
result2 = Math.Sqrt(aValue); // result2 = 8.88403061678651
Console.Write(“aValue rounded to 2 decimal places”
+ “ is {0}”, Math.Round(aValue, 2));

aValue rounded to 2
decimal places is 78.93
C# Programming: From Problem Analysis to Program Design 33
Method Calls That Return Values
Line 1 int aValue = 200; In an assignment
Line 2 int bValue = 896; statement
Line 3 int result;
Line 4 result = Math.Max(aValue, bValue); // result = 896
Line 5 result += bValue * Part of arithmetic expression
Line 6 Math.Max(aValue, bValue) – aValue;
// result = 896 + (896 * 896 - 200) (result = 803512)
Line 7 Console.WriteLine(“Largest value between {0} ”
Line 8 + “and {1} is {2}”, aValue, bValue,
Line 9 Math.Max(aValue, bValue));
Argument to
another method call
C# Programming: From Problem Analysis to Program Design 34
Writing Your Own Class
Methods
[modifier(s)] returnType MethodName ( parameterList )
{
// body of method - consisting of executable statements
}
• void Methods
– Simplest to write
– No return statement

C# Programming: From Problem Analysis to Program Design 35


class
method
Writing Your Own Class
Methods – void Types
public static void DisplayInstructions( )
{
Console.WriteLine(“This program will determine how ”
+ “much carpet to purchase.”);
Console.WriteLine( );
Console.WriteLine(“You will be asked to enter the ”
+ “ size of the room and ”);
Console.WriteLine(“the price of the carpet, ”
+ ”in price per square yards.”);
Console.WriteLine( ); A call to this method looks
} like:
C# Programming: From Problem Analysis to Program Design
DisplayInstructions( ); 36
Writing Your Own Class
Methods – void Types (continued)
public static void DisplayResults(double squareYards,
double pricePerSquareYard)
{
Console.Write(“Total Square Yards needed: ”);
Console.WriteLine(“{0:N2}”, squareYards);
Console.Write(“Total Cost at {0:C} “, pricePerSquareYard);
Console.WriteLine(“ per Square Yard: {0:C}”,
(squareYards * pricePerSquareYard));
}
• static method called from within the class where it resides
• To invoke method – DisplayResults(16.5, 18.95);
C# Programming: From Problem Analysis to Program Design 37
Value-Returning Method
• Has a return type other than void
• Must have a return statement
– Compatible value
• Zero, one, or more data items may be passed as
arguments
• Calls can be placed:
– In assignment statements
– In output statements
– In arithmetic expressions
– Or anywhere a value can be used
C# Programming: From Problem Analysis to Program Design 38
Value-Returning Method (continued)
public static double GetLength( )
{
string inputValue; Return
int feet, inches; type→
double
Console.Write(“Enter the Length in feet: ”);
inputValue = Console.ReadLine( );
feet = int.Parse(inputValue);
Console.Write(“Enter the Length in inches: “);
inputValue = Console.ReadLine( );
inches = int.Parse(inputValue); double
return (feet + (double) inches / 12); returned
}
C# Programming: From Problem Analysis to Program Design 39
CarpetExampleWithClassMethods
/* CarpetExampleWithClassMethods.cs */
using System;
namespace CarpetExampleWithClassMethods
{
public class CarpetWithClassMethods
{
public static void Main( )
{
double roomWidth, roomLength, pricePerSqYard,
noOfSquareYards;
DisplayInstructions( );
// Call getDimension( ) to get length
roomLength = GetDimension(“Length”);
C# Programming: From Problem Analysis to Program Design 40
CarpetExampleWithClassMethods
(continued)
/* CarpetExampleWithClassMethods.cs */
using System;
namespace CarpetExampleWithClassMethods
{
public class CarpetWithClassMethods
{

C# Programming: From Problem Analysis to Program Design 41


public static void Main( )
{
double roomWidth, roomLength, pricePerSqYard,
noOfSquareYards;
DisplayInstructions( );

// Call getDimension( ) to get length


roomLength = GetDimension(“Length”);

roomWidth = GetDimension(“Width”);
pricePerSqYard = GetPrice( );
noOfSquareYards =
DetermineSquareYards(roomWidth, roomLength);
DisplayResults(noOfSquareYards, pricePerSqYard);
}
C# Programming: From Problem Analysis to Program Design 42
public static void DisplayInstructions( )
{
Console.WriteLine(“This program will determine how much "
+ “carpet to purchase.”);
Console.WriteLine( );
Console.WriteLine("You will be asked to enter the size of ”
+ “the room ");
Console.WriteLine(“and the price of the carpet, in price per”
+ “ square yds.”);
Console.WriteLine( );
}

C# Programming: From Problem Analysis to Program Design 43


public static double GetDimension(string side )
{
string inputValue; // local variables
int feet, // needed only by this
inches; // method
Console.Write("Enter the {0} in feet: ", side);
inputValue = Console.ReadLine( );
feet = int.Parse(inputValue);
Console.Write("Enter the {0} in inches: ", side);
inputValue = Console.ReadLine( );
inches = int.Parse(inputValue);

// Note: cast required to avoid int division


return (feet + (double) inches / 12);
}
C# Programming: From Problem Analysis to Program Design 44
public static double GetPrice( )
{
string inputValue; // local variables
double price;
Console.Write(“Enter the price per Square Yard: ");
inputValue = Console.ReadLine( );
price = double.Parse(inputValue);
return price;
}

C# Programming: From Problem Analysis to Program Design 45


public static double DetermineSquareYards
(double width, double length)
{
const int SQ_FT_PER_SQ_YARD = 9;
double noOfSquareYards;
noOfSquareYards = length * width / SQ_FT_PER_SQ_YARD;
return noOfSquareYards;
}

public static double DeterminePrice (double squareYards,


double pricePerSquareYard)
{
return (pricePerSquareYard * squareYards);
}

C# Programming: From Problem Analysis to Program Design 46


public static void DisplayResults (double squareYards,
double pricePerSquareYard)
{
Console.WriteLine( );
Console.Write(“Square Yards needed: ”);
Console.WriteLine("{0:N2}", squareYards);
Console.Write("Total Cost at {0:C} ", pricePerSquareYard);

Console.WriteLine(“ per Square Yard: {0:C}”,


DeterminePrice(squareYards,
pricePerSquareYard));
}
} // end of class
} // end of namespace

C# Programming: From Problem Analysis to Program Design 47


CarpetExampleWithClassMethods
(continued)

Figure 4-7 Output from CarpetExampleWithClassMethods

C# Programming: From Problem Analysis to Program Design 48


The Object Concept
• Class
• Entity
• Abstraction
– Attributes (data)
– Behaviors (processes on the data)

• Private member data (fields)


– Public method members
C# Programming: From Problem Analysis to Program Design 49
Writing Your Own Instance
Methods
• Do not use static keyword
– Static – class method
• Constructor
– Do not return a value
– void is not included
– Same identifier as the class name
– Overloaded methods
– Default constructor
• No arguments

C# Programming: From Problem Analysis to Program Design 50


Calling the Constructor
• Default values are assigned to variables of the
value types when no arguments are sent

C# Programming: From Problem Analysis to Program Design 51


Writing Your Own Instance
Methods (continued)
• Accessor (getter)
– Returns the current value
– Standard naming convention → prefix with “get”
– Accessor for noOfSquareYards is
GetNoOfSquareYards( )
• Mutators (setters)
– Normally includes one parameter
– Method body → single assignment statement
– Standard naming convention → prefix with ”Set”

C# Programming: From Problem Analysis to Program Design 52


Accessor and Mutator Examples
public double GetNoOfSquareYards( ) Accessor
{
return noOfSquareYards;
}

public void SetNoOfSquareYards(double squareYards)


{
Mutator
noOfSquareYards = squareYards;
}

C# Programming: From Problem Analysis to Program Design 53


Properties
• Looks like a data field
– More closely aligned to methods

• Standard naming convention in C# for properties


– Use the same name as the instance variable or field,
but start with uppercase character

C# Programming: From Problem Analysis to Program Design 54


Calling Instance Methods
• Calling the Constructor
ClassName objectName = new ClassName(argumentList);
or
ClassName objectName;
objectName = new ClassName(argumentList);
• Keyword new used as operator to call constructor
methods
CarpetCalculator plush = new CarpetCalculator ( );
CarpetCalculator pile =
new CarpetCalculator (37.90, 17.95);
CarpetCalculator berber = new CarpetCalculator (17.95);
C# Programming: From Problem Analysis to Program Design 55
Calling Accessor and Mutator
Methods
• Method name is preceded by the object name
berber.SetNoOfSquareYards(27.83);
Console.WriteLine(“{0:N2}”,
berber.GetNoOfSquareYards( ));
• Using properties
PropertyName = value;
and
Console.Write(“Total Cost at {0:C} ”,
berber.Price);

C# Programming: From Problem Analysis to Program Design 56


ToString( ) method
• All user-defined classes inherit four methods from
the object class
– ToString( )
– Equals( )
– GetType( )
– GetHashCode( )
• ToString( ) method is called automatically by
several methods
– Write( )
– WriteLine( ) methods
• Can also invoke or call the ToString( ) method
directly
C# Programming: From Problem Analysis to Program Design 57
ToString( ) method (continued)
• Returns a human-readable string
• Can write a new definition for the ToString( )
method to include useful details
public override string ToString( )
{ // return string value }
• Keyword override added to provide new
implementation details

C# Programming: From Problem Analysis to Program Design 58


Types of Parameters
• Call by value
– Copy of the original value is made
• Other types of parameters
– ref
– out
– params
• ref and out cause a method to refer to the same
variable that was passed into the method
C# Programming: From Problem Analysis to Program Design 59
Types of Parameters (continued)

Figure 4-10 Call by reference versus value


C# Programming: From Problem Analysis to Program Design 60

You might also like