Chapter 3: Learning Just Enough C# and VB.NET: Types and Members

75

Since PrintMethodInstance is an instance method, you call it differently; through an instance of its containing type, which the following code repeats from Listing 3-5:

C#:

MessagePrinter msgPrint = new MessagePrinter(); msgPrint.PrintMessageInstance();

VB:

Dim msgPrint As New MessagePrinter() msgPrinter.PrintMessageInstance()

As this example shows, the type of msgPrint is MessagePrinter. Using the statement new MessagePrinter creates a new instance of MessagePrinter at runtime, which is assigned to the msgPrint variable. Now that you’ve created an instance of a MessagePrinter and msgPrint has a reference to that instance, you can call the instance method, PrintMessageInstance, via the msgPrint variable. Next, let’s look at how to add parameters to a method and discuss why that’s important.

Declaring Parameters and Passing Arguments

Passing parameters to a method is a great way to make code more reusable. For example, what if you had a method that printed a report containing the names of all customers? It wouldn’t make sense to create one method for each customer, especially when the list changes all the time. Listing 3-6 shows a method that takes a list of customers and prints a report with customer names.

Listing 3-6 Declaring a method that takes parameters

C# (Program.cs):

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

namespace FirstProgram

{

class Program

{

static void Main(string[] args)

Page 98
Image 98
Microsoft 9GD00001 manual Declaring Parameters and Passing Arguments, Listing 3-6 Declaring a method that takes parameters