Professional Documents
Culture Documents
• Using Methods
• Using Parameters
• Using Overloaded Methods
• Defining Methods
• Calling Methods
• Using the return Statement
• Using Local Variables
• Returning Values
A method contains:
• The method specification (access, return type, and signature)
• The method body (code)
Method signature:
To call a method:
• Specify the method name
• Provide an argument for each parameter
• Handle the return value
Example method
bool LockReport(string reportName, string userName)
{
...;
}
Console.WriteLine("Hello");
if (numBeans < 10)
return;
Console.WriteLine("World");
}
• Declaring parameters
– Place between parentheses after method name
– Define type and name for each parameter
• Calling methods with parameters
– Supply a value for each parameter
[5.2.1 Declaring Parameters / 5.2.2 Declaring Parameters]
in • Pass by value
in
• Pass by reference
out
void MyMethod(
int intData, float floatData, int moreIntData = 99)
{
...
}
void MyMethod(
int intData, float floatData = 101.1F, int moreIntData = 99)
{
...
}
• Mechanisms
– Pass by value is most common
– Method return value is useful for single values
– Use ref and/or out for multiple return values
– Only use ref if data is transferred both ways
• Efficiency
– Pass by value is generally the most efficient
Forms
Signature No Effect on
Definition Signature
• Name of
• Name of method parameter
• Parameter type • Return type of
• Parameter method
modifier
Example [5.3.7 Parameter Array / 5.3.8 Parameter Array / 5.3.9 Parameter Array]
Method call
int sum = Add(99, 2, 55, -26);
© Copyright 2011 Avanade Inc. All Rights Reserved. 28
Refactoring Code into a Method
LogMessage(messageContents, filePath);
...
private void LogMessage(string messageContents, string filePath)
{
...
}
© Copyright 2011 Avanade Inc. All Rights Reserved. 29
Testing a Method
int Calculate(int operandOne, int operandTwo)
{
int result = 0;
return result;
} Create Unit Test
Wizard
[TestMethod()]
public void CalculateTest()
{
Program target = new Program();
int operandOne = 0;
int operandTwo = 0;
int expected = 0;
int actual;
actual = target.Calculate(operandOne, operandTwo);
Assert.AreEqual(expected, actual);
...
} © Copyright 2011 Avanade Inc. All Rights Reserved. 30
Demonstration: Refactoring and Testing a
Method
In this demonstration, you will:
• Open the existing application and view the existing code
• Refactor an existing code block
• Generate a unit test for the GenerateRandomNumbers
method
• Examine the auto-generated unit test method
• Modify the auto-generated unit test method
• Run the unit test
• Review Questions
• Best Practices