11. Methods
Each batch of iron needs an ore calculation. Give that calculation a name so your spell can call it wherever it is needed. Custom helper methods unlock with Moonstone research.
Calculate required ore
Each iron needs 2 ore. Define a method called RequiredOre that accepts an iron quantity and doubles it.
public class Program : ArcaneProgram
{
private int RequiredOre(int iron)
{
return iron * 2;
}
public void OnStart()
{
int needed = RequiredOre(5);
if (needed == 10)
{
Workshop.Log.Write("Ten ore required.");
}
}
}Write the RequiredOre definition outside OnStart but inside Program's braces. Defining it does not run it. Calling RequiredOre(5) runs it.
Pass a value and receive a result
- OnStart calls RequiredOre and passes 5.
- The parameter
int ironreceives 5. - The method calculates
iron * 2. - return sends 10 back to the call site.
- needed receives 10, then execution continues to the if statement.
iron is a parameter. The value 5 supplied in the call is an argument. The value sent back is the return value. return sends a result to the caller without displaying it on screen.
Read the declaration
In private int RequiredOre(int iron), the first int is the return type. private makes the method available inside Program. OnStart is public so the game can call it.
void in OnStart means it returns no value. return ends the current method. To end a method without returning a value, write return;.
iron is available inside RequiredOre, while needed is available inside OnStart. The region where you can use a name is its scope.
Exercise
Use RequiredOre to calculate the ore needed for 8 iron. How do you change the call, the comparison and the message?
Show example solutionHide example solution
Call RequiredOre(8), check needed == 16, and change the message to Sixteen ore required. The method definition stays the same. It calculates 8 × 2 and returns 16.
