Microsoft 9GD00001 Computer Accessories User Manual


 
78 Microsoft Visual Studio 2010: A Beginner’s Guide
VB:
Sub PrintCustomerReport(
ByVal customers As String(),
Optional ByVal title As String = "Customer Report")
Console.WriteLine(title)
Console.WriteLine()
For Each name In customers
Console.WriteLine(name)
Next
End Sub
The preceding code requires callers to pass an array of customers, but it does not
require a title. When writing methods, optional parameters must be listed last. Here’s
a method call without the optional parameter:
C#:
custProg.PrintCustomerReport(customerNames);
VB:
msgPrint.PrintCustomerReport(customerNames)
Because the caller didn’t pass an argument for title, the value of title inside of
PrintCustomerReport becomes the default value assigned to the title parameter.
In addition to passing arguments to methods, you can receive values returned from
methods.
Returning Data and Using Method Results
It is common to call methods that return values. To demonstrate the proper syntax,
Listing 3-7 contains a method that accepts an int and returns the squared value of
that int. Calling code then assigns the return value from the method to a variable and
displays the value on the console window. Create a new class named Calc.cs or Calc.
vb to hold the new method.
Listing 3-7 Returning values from methods
C# (Program.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;