Chapter 3. We Have Our Methods

In This Chapter

  • Defining a method

  • Passing arguments to a method

  • Getting results back

  • Reviewing the WriteLine() method

Programmers need to be able to break large programs into smaller chunks that are easy to handle. For example, the programs contained in previous chapters of this minibook reach the limit of the amount of programming information a person can digest at one time.

C# lets you divide your class code into chunks known as methods. Properly designed and implemented methods can greatly simplify the job of writing complex programs.

Note

A method is equivalent to a function, procedure, or subroutine in other languages. The difference is that a method is always part of a class.

Defining and Using a Method

Consider the following example:

class Example
{
  public int anInt;                  // Nonstatic
  public static int staticInt        // Static
  public void InstanceMethod()       // Nonstatic
  {
    Console.WriteLine("this is an instance method");
  }
  public static void ClassMethod()   // Static
  {
    Console.WriteLine("this is a class method");
  }
}

The element anInt is a data member, just like those shown in Book I. However, the element InstanceMethod() is new. InstanceMethod() is known as an instance method (duh!), which is a set of C# statements that you can execute by referencing the method's name. This concept is best explained by example — even I'm confused right now. (Main() and WriteLine() are used in nearly every example in this book, and they're methods.)

Note: The distinction between static ...

Get C# 2010 All-in-One For Dummies® now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.