You are on page 1of 32

Module 5:

Methods and Parameters

First Name Last Name 20pt Client logo 1 Client logo 2


Job Title 20pt

Today’s Date 18pt

© Copyright 2011 Avanade Inc. All Rights Reserved. 1


The Avanade name and logo are registered trademarks in the US and other countries.
Module Overview

• Using Methods
• Using Parameters
• Using Overloaded Methods

© Copyright 2011 Avanade Inc. All Rights Reserved. 2


Lesson 1:
Using Methods

© Copyright 2011 Avanade Inc. All Rights Reserved. 3


Using Methods

• Defining Methods
• Calling Methods
• Using the return Statement
• Using Local Variables
• Returning Values

© Copyright 2011 Avanade Inc. All Rights Reserved. 4


What Is a Method?

A method is a class member that contains a code block that represents


• Level one Arial typeface 24pt
an action:
– Level
• All executable
two Arial code belongs22pt
typeface to a method
• ALevel
C# application
three Arial must have at20pt
typeface least one method
• Methods can be defined for private use by a type, or for
– Level four Arial typeface 18pt
public use by other types
• Level five Arial typeface 16pt
• Text should never be set below 14pt, with the exception of
“Source”
The Main text which
method can
defines the be setpoint
starting at 9pt.
for an application

C# supports instance and static methods

Instance method Static method


int count = 99; string strCount = “99”;
string strCount = count =
count.ToString(); Convert.ToInt32(strCount);
© Copyright 2011 Avanade Inc. All Rights Reserved. 5
Creating a Method

A method contains:
• The method specification (access, return type, and signature)
• The method body (code)

Method signature:

1 Name (Pascal case) Each method signature must be


unique in a programming type
2 Parameters (camel case)

Example [5.1.1 Creating Method / 5.1.2 Creating Method]

bool LockReport(string userName)


{
bool success = false;
// Perform some processing here.
return success;
}
© Copyright 2011 Avanade Inc. All Rights Reserved. 6
Calling a Method

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)
{
...;
}

Method call Note:


Arguments are
bool isReportLocked = evaluated in left-
LockReport("Medical Report", “Don Hall");
to-right order
© Copyright 2011 Avanade Inc. All Rights Reserved. 7
Calling Methods
• After you define a method, you can:
[5.1.3 Calling Method]

– Call a method from within the same class


Use method’s name followed by a parameter list in parentheses
[5.1.4 Calling Method]

– Call a method that is in a different class


You must indicate to the compiler which class contains the method
to call
The called method must be declared with the public keyword
[5.1.5 Nested Calls]

– Use nested calls


Methods can call methods, which can call other methods, and so
on

© Copyright 2011 Avanade Inc. All Rights Reserved. 8


Returning Values

• Declare the method with non-void type


• Add a return statement with an expression
– Sets the return value
– Returns to caller
• Non-void methods must return a value
[5.1.6 Using Return \ 5.1.7 Using Return]

static int TwoPlusTwo( ) { int x;


int a,b; x = TwoPlusTwo( );
a = 2; Console.WriteLine(x);
b = 2;
return a + b;
}

© Copyright 2011 Avanade Inc. All Rights Reserved. 9


Using the return Statement

• Immediate return [5.1.8 Using Return]

• Return with a conditional statement [5.1.9 Using Return]

static void ExampleMethod( )


{
int numBeans;
//...

Console.WriteLine("Hello");
if (numBeans < 10)
return;
Console.WriteLine("World");
}

© Copyright 2011 Avanade Inc. All Rights Reserved. 10


Using Local Variables

• Local variables [5.1.10 Local Variables]

– Created when method begins


– Private to the method
– Destroyed on exit

• Shared variables [5.1.11 Local Variables]

– Class variables are used for sharing

• Scope conflicts [5.1.12 Local Variables]

– Compiler will not warn if local and class names clash

© Copyright 2011 Avanade Inc. All Rights Reserved. 11


Lesson 2:
Using Parameters

© Copyright 2011 Avanade Inc. All Rights Reserved. 12


Using Parameters

• Declaring and Calling Parameters


• Mechanisms for Passing Parameters
• Pass by Value
• Pass by Reference
• Output Parameters
• Using Variable-Length Parameter Lists
• Guidelines for Passing Parameters
• Using Recursive Methods

© Copyright 2011 Avanade Inc. All Rights Reserved. 13


Declaring and Calling Parameters

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

static void MethodWithParameters(int n, string y)


{ ... }

MethodWithParameters(2, "Hello, world");

© Copyright 2011 Avanade Inc. All Rights Reserved. 14


Mechanisms for Passing Parameters

• Three ways to pass parameters

in • Pass by value

in
• Pass by reference
out

out • Output parameters

© Copyright 2011 Avanade Inc. All Rights Reserved. 15


Pass by Value

• Default mechanism for passing parameters:


– Parameter value is copied
– Variable can be changed inside the method
– Has no effect on value outside the method
– Parameter must be of the same type or compatible type
[5.2.3 Pass By Value]

static void AddOne(int x)


{
x++; // Increment x
}
static void Main( )
{
int k = 6;
AddOne(k);
Console.WriteLine(k); // Display the value 6, not 7
}
© Copyright 2011 Avanade Inc. All Rights Reserved. 16
Pass by Reference

• What are reference parameters?


– A reference to memory location
• Using reference parameters
– Use the ref keyword in method declaration and call
– Match types and variable values
– Changes made in the method affect the caller
– Assign parameter value before calling the method
[5.2.4 Pass By Reference]

© Copyright 2011 Avanade Inc. All Rights Reserved. 17


Output Parameters

• What are output parameters?


– Values are passed out but not in
• Using output parameters
– Like ref, but values are not passed into the method
– Use out keyword in method declaration and call
[5.2.5 Out Parameter]

static void OutDemo(out int p)


{
// ...
}
int n;
OutDemo(out n);

© Copyright 2011 Avanade Inc. All Rights Reserved. 18


What Are Optional Parameters?
Optional parameters enable you to define a method and
provide default values for the parameters in the parameter list:
• They are useful for interoperating with other technologies that support
optional parameters
• They can provide an alternative implementation where overloading is
not appropriate

Example [5.2.6 Optional Parameter]

void MyMethod(
int intData, float floatData, int moreIntData = 99)
{
...
}

// Arguments provided for all three parameters


MyMethod(10, 123.45, 99);

// Arguments provided for 1st two parameters only


MyMethod(100, 54.321);
© Copyright 2011 Avanade Inc. All Rights Reserved. 19
Calling a Method by Using Named Arguments

Specify parameters by name:


• Arguments can occur in any order
• Omitted arguments are assigned default values if the
corresponding parameter is optional

Example [5.2.7 Named Argument]

void MyMethod(
int intData, float floatData = 101.1F, int moreIntData = 99)
{
...
}

MyMethod(moreIntData: 100, intData: 10);


// floatData is assigned default value
© Copyright 2011 Avanade Inc. All Rights Reserved. 20
Guidelines for Passing Parameters

• 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

© Copyright 2011 Avanade Inc. All Rights Reserved. 21


Using Recursive Methods

• A method can call itself


– Directly
– Indirectly

• Useful for solving certain problems


[5.2.8 Recursive Method / 5.2.9 Recursive Method]

© Copyright 2011 Avanade Inc. All Rights Reserved. 22


Lesson 3:
Using Overloaded Methods

© Copyright 2011 Avanade Inc. All Rights Reserved. 23


Using Overloaded Methods

• Declaring overloaded methods


• Method signatures
• Using overloaded methods

© Copyright 2011 Avanade Inc. All Rights Reserved. 24


Creating and Calling Overloaded Methods
An overloaded method:
• Has the same name as an existing method
• Should perform the same operation as the existing method
• Uses different parameters to perform the operation

The compiler invokes the version that is appropriate to the arguments


that are specified when the method is called

Example [5.3.2 Overloaded Methods / 5.3.3 Overloaded Methods]

void Deposit(decimal amount)


{
_balance += amount; The signature of
} the Deposit method
is different for each
void Deposit(int dollars, int cents) implementation
{
_balance += dollars + (cents / 100.0m);
}
© Copyright 2011 Avanade Inc. All Rights Reserved. 25
Using Overloaded Methods

• Consider using overloaded methods when:


[5.3.1 Overloaded Methods]

– You have similar methods that require different parameters


– You want to add new functionality to existing code
• Do not overuse because:
– Hard to debug
– Hard to maintain

© Copyright 2011 Avanade Inc. All Rights Reserved. 26


Method Signatures

• Method signatures must be unique within a class


• Signature definition
[5.3.4 Method Signatures / 5.3.5 Method Signatures / 5.3.6 Method Signatures]

Forms
Signature No Effect on
Definition Signature
• Name of
• Name of method parameter
• Parameter type • Return type of
• Parameter method
modifier

© Copyright 2011 Avanade Inc. All Rights Reserved. 27


Using Parameter Arrays

Overloading may not be possible or appropriate if a method can take a


variable number of arguments

Example [5.3.7 Parameter Array / 5.3.8 Parameter Array / 5.3.9 Parameter Array]

int Add(params int[] data)


{
int sum = 0;
for (int i = 0; i < data.Length; i++)
{
sum += data[i];
}
return sum;
}

Method call
int sum = Add(99, 2, 55, -26);
© Copyright 2011 Avanade Inc. All Rights Reserved. 28
Refactoring Code into a Method

Select the code that you want to extract to a


1
method, right-click, point to Refactor, and then
click Extract Method

In the Extract Method dialog box, in the New


2
method name box, type a name for the method,
and then click OK

Example of refactored output [5.3.10 Refactored Method / 5.3.11 Refactored 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;

// Perform some calculation.

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

© Copyright 2011 Avanade Inc. All Rights Reserved. 31


Module Review and Takeaways

• Review Questions
• Best Practices

© Copyright 2011 Avanade Inc. All Rights Reserved. 32

You might also like