Microsoft 9GD00001 Computer Accessories User Manual


 
74 Microsoft Visual Studio 2010: A Beginner’s Guide
Listing 3-5 has two types of methods, static and instance. In VB, shared methods are
the same as static. You can tell which type of method each is because static methods have
the static modifier (shared in VB), but instance methods don’t have a static (or shared in
VB) modifier. First, let’s look at the static (shared) method declaration, and then you’ll see
how it’s called.
The static (shared in VB) method, PrintMessageStatic (PrintMessageShared in VB)
has a public access modifier, which means that any other code using the containing class,
MessagePrinter, will be able to see the method. If you didn’t include the public access
modifier, the method would automatically default to being private and only other code
residing within the MessagePrinter class would be able to use that method.
PrintMessageStatic has a void keyword, meaning that this method does not return a
value. In VB, you indicate that a method does not return a value by making it a Sub, as
was done in Listing 3-5. Later, you’ll learn how to create a method that does return values
to its calling code that invokes this method. The empty parameter list appended to the
PrintMessageStatic (PrintMessageShared in VB) means that there are not any parameters
for this method. Parameters allow callers to pass information to the method; a subject
we’ll discuss soon.
Within the method block, you can see that there is a Console.WriteLine statement.
You can add as many statements as you need for the purpose of the method. Next, we’ll
examine how PrintMessageStatic (PrintMessageShared in VB) is called, which the
following code repeats from Listing 3-5:
C#:
Program.PrintMessageStatic();
VB:
MessagePrinter.PrintMessageShared()
Viewing the preceding example, which shows a statement inside of the Main method,
you can see the call to Program.PrintMessageStatic (PrintMessageShared in VB).
Notice that the class (aka type) that contains all the methods is named MessagePrinter.
In C#, a static method is called through its containing type, which is why you call
PrintMessageStatic with the Program prefix. In VB, you can invoke shared methods
through either the method’s type or an instance of that type. We discuss instance
methods next.
The next method, PrintMessageInstance, is an instance method; it has no static
modifier. The rest of the method definition mirrors that of the PrintMessageStatic method.