1.3.1 Understanding Methods

Video: Introduction to Methods (12:41)
Methods Represent Behavior

Fields describe object state.

Methods describe actions an object can perform.

For a Team class:

Activity diagram showing fields name, score, then methods DisplayName, ResetScore.
FieldsNameScore.
  • New
  • Changed
  • Removed

This is a major step in object-oriented programming:

objects have state and behavior.

A Method Belongs to a Class

A simple method can appear inside a class:

class Team
{
    public string name;

    public void DisplayName()
    {
        System.Console.WriteLine(this.name);
    }
}

The method belongs to Team.

When it runs for a specific Team object, this refers to that current Team.

Call the Method Through an Object

If:

Team team1 = new Team();
team1.name = "Wildcats";

then:

team1.DisplayName();

asks the team1 object to perform its DisplayName behavior.

Conceptually:

Activity diagram showing team1, then DisplayName(), then method statements execute.
Team.
  • New
  • Changed
  • Removed
Method Calls Change Execution Flow

Normally, execution reaches the call:

team1.DisplayName();

C# enters the method, executes its statements, and then continues after the call.

Detailed nested-call tracing comes in the next batch.

Methods Can Use the Current Object's Fields

Inside Team:

this.name

accesses the current Team object's field.

This connects prior object concepts to behavior.

Methods Are Defined Once and Used by Many Objects

If both team1 and team2 are Team objects:

team1.DisplayName();
team2.DisplayName();

the same method definition can execute for different current objects.

The object's state determines what the method sees through this.