Methods and Behaviors: C# Programming
Methods and Behaviors: C# Programming
Methods and Behaviors: C# Programming
Behaviors
• protected
• internal
• protected internal
• private
C# Programming: From Problem Analysis to Program Design 7
Level of Accessibility
Compatible value
(double) returned
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
Method signature(s)
Method signature(s)
and description
and description
string
parameter
18 different Write( )
methods
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
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( );
}