72Microsoft Visual Studio 2010: A Beginner’s Guide

Just type in the class name in the field and press ENTER. The carat will locate to the inside of the class block. Now that you know how to create classes, you’ll need to know how to add members, starting with methods.

Writing Methods

You can divide your algorithms into blocks of code called methods. In different programming languages, methods are called functions, procedures, or subroutines. I’ll use the term method as a generic term, except when I need to be more specific. You’ve already used methods when coding Console.WriteLine, where WriteLine is a method of the Console class. A method contains one or more statements. Reasons for creating methods include the ability to modularize your code, isolate complex operations in one place, or group a common operation that can be reused in multiple places. The following sections show you how to declare and use methods.

Declaring and Using a Method

To start off, I’ll show you a very simple method so that you can see the syntax and understand the program flow. Listing 3-5 will move the Console.Writeline statement from the Main method discussed in Chapter 2 into a new containing method and then add a statement to the Main method that calls the new method.

Listing 3-5 Declaring and calling a method

C# (Program.cs)

using System;

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

using System.Text;

namespace FirstProgram

{

class Program

{

static void Main(string[] args)

{

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

}

}

Page 95
Image 95
Microsoft 9GD00001 manual Writing Methods, Declaring and Using a Method, Listing 3-5 Declaring and calling a method