Professional Documents
Culture Documents
In previous lessons of this tutorial, all of our functionality for each program resided in
the Main() method. While this was adequate for the simple programs we used to learn earlier
concepts, there is a better way to organize your program, using methods. A method helps you
separate your code into modules that perform a given task. The objectives of this lesson are as
follows:
Understand the structure of a method.
Know the difference between static and instance methods.
Learn to instantiate objects.
Learn how to call methods of an instantiated object.
Understand the 4 types of parameters.
Learn how to use the this reference.
Method Structure
Methods are extremely useful because they allow you to separate your logic into different units. You
can pass information to methods, have it perform one or more statements, and retrieve a return
value. The capability to pass parameters and return values is optional and depends on what you
want the method to do. Here’s a description of the syntax required for creating a method:
attributes modifiers return-type method-name(parameters )
{
statements
}
We defer discussion of attributes and modifiers to a later lesson. The return-type can be any C#
type. It can be assigned to a variable for use later in the program. The method name is a unique
identifier for what you wish to call a method. To promote understanding of your code, a method
name should be meaningful and associated with the task the method performs. Parameters allow
you to pass information to and from a method. They are surrounded by parenthesis. Statements
within the curly braces carry out the functionality of the method.
Listing 5-1. One Simple Method: OneMethod.cs
using System;
class OneMethod
{
public static void Main()
{
string myChoice;
do
{
myChoice = om.getChoice();
Console.ReadLine();
Console.WriteLine();
class Address
{
public string name;
public string address;
}
class MethodParams
{
public static void Main()
{
string myChoice;
do
{
// show menu and get input from user
myChoice = mp.getChoice();
switch(myChoice)
{
case "A":
case "a":
addr.name = "Joe";
addr.address = "C# Station";
this.addAddress(ref addr);
break;
case "D":
case "d":
addr.name = "Robert";
this.deleteAddress(addr.name);
break;
case "M":
case "m":
addr.name = "Matt";
this.modifyAddress(out addr);
Console.WriteLine("Name is now {0}.", addr.name);
break;
case "V":
case "v":
this.viewAddresses("Cheryl", "Joe", "Matt",
"Robert");
break;
case "Q":
case "q":
Console.WriteLine("Bye.");
break;
default:
Console.WriteLine("{0} is not a valid choice",
myChoice);
break;
}
}