
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
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
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)