Chapter 3: Learning Just Enough C# and VB.NET: Types and Members 77
VB (MessagePrinter.vb):
Public Class MessagePrinter
Sub PrintCustomerReport(ByVal customers As String(), ByVal title
As String)
Console.WriteLine(title)
Console.WriteLine()
For Each name In customers
Console.WriteLine(name)
Next
End Sub
End Class
Parameters are a comma-separated list of identifiers, along with the type of each
identifier, which clearly indicates what type of parameter the method is expecting. In
Listing 3-6, the PrintCustomerReport method has two parameters: title of type string and
customers of type string array. The method displays the title in the console window when
you run the program, displays a blank line, and then iterates through the list, displaying
each customer name to the console.
You can see how the Main method creates a new instance of MessagePrinter,
which msgPrint points to, and then calls PrintCustomerReport using msgPrint. The
arguments being passed, reportTitle and customerNames, match the position and types
of the parameters for PrintCustomerReport, which are of the correct types that the
PrintCustomerReport method is expecting.
In the preceding example, the calling code must provide arguments, actual data,
for all parameters. However, you can specify parameters as being optional, allowing
you to omit arguments for the optional parameters if you like. Here’s a modification to
PrintCustomerReport where the title becomes an optional parameter:
C#:
public void PrintCustomerReport(
string[] customers, string title = "Customer Report")
{
Console.WriteLine(title);
Console.WriteLine();
foreach (var name in customers)
{
Console.WriteLine(name);
}
}