A method gives an object a named behavior that code can call.
Consider:
public void DisplayRoster()
{
System.Console.WriteLine(this.name);
}The first line tells C# how the method is declared:
At this stage, the parameter list is empty. Parameters are introduced in Module 1.4.
The declaration tells you important things about the method before you inspect the statements inside it.
For:
public void DisplayRoster()A useful method name should help a reader predict the behavior the method is responsible for.
For example:
DisplayRoster()
ResetScore()
StartMatch()Each name describes an action rather than a vague idea.
Consider:
public void DisplayName()
{
System.Console.WriteLine(this.name);
}The return type is:
voidThat tells C# that the method does not send a result value back to the calling code.
void does not mean that the method does nothing.
It means:
The braces contain the statements that execute when the method is called:
public void DisplayName()
{
System.Console.WriteLine(this.name);
}In this example, the method's job is to display the current object's name.
The declaration identifies the behavior. The body defines the instructions that perform it.
If team1 refers to a Team object, this statement:
team1.DisplayName();asks that object to execute its DisplayName method.
The call uses the method name and parentheses:
DisplayName()Execution moves into the method body, the statements run, and then execution continues with the statement after the call.
This connects the two sides:
A method does not need to return a value in order to have an effect.
For example:
public void ResetScore()
{
this.score = 0;
}This method returns no value.
It still changes the current Team object's state by assigning 0 to score.
So these are different questions:
For now, write methods with empty parameter lists:
public void ResetScore()
{
this.score = 0;
}
public void DisplayName()
{
System.Console.WriteLine(this.name);
}The parentheses still matter even though there is nothing between them.
They are part of the method declaration and appear again when the method is called:
team1.ResetScore();
team1.DisplayName();Suppose the requirement is:
A focused method could be:
public void ResetScore()
{
this.score = 0;
}The declaration and body work together:
When you encounter a method, ask:
For the methods in this module, the most important pattern is:
public void MethodName()
{
action statements
}A well-written void method gives one focused behavior a clear name and a clear set of instructions.
The declaration tells you how the method is identified and that it returns no value. The body tells you what the method actually does.
When another object or statement calls the method, that behavior executes and control then returns to the caller.