🎯 What you will learn
- Define and call methods
- Use return types and parameters
- Use optional parameters and => bodies
👋 Let’s get started!
Methods keep your game code organized 🛠️: one method to attack, one to heal, one to level up. C# adds neat extras like default parameter values.
🪜 Step by step
1. 🛠️ Define & call
Return type, name, parameters.
static int Add(int a, int b)
{
return a + b;
}
Console.WriteLine(Add(2, 3));
2. ⚡ Expression bodies
One-line methods can use =>.
static int Square(int n) => n * n;
Console.WriteLine(Square(9));
3. 🎚️ Default values
Parameters can have defaults.
static void Greet(string name = "traveler")
=> Console.WriteLine($"Welcome, {name}!");
Greet();
Greet("Ava");
🧪 Try it!
Read the code, guess what it prints, then press 👀 Show output.
Damage calculator
static int Damage(int attack, int defense, bool critical = false)
{
int dmg = Math.Max(1, attack - defense);
return critical ? dmg * 2 : dmg;
}
Console.WriteLine(Damage(20, 8));
Console.WriteLine(Damage(20, 8, critical: true));
Console.WriteLine(Damage(5, 30));Heal method
static int Heal(int hp, int amount)
{
return Math.Min(100, hp + amount);
}📖 Key words
Tap a card to flip it over!
- Method
- Reusable named code 🛠️
- static
- Belongs to the class, not an object 🏛️
- =>
- Short method body ⚡
- Named argument
- Passing a value by name: critical: true 🏷️
🏆 Challenge
Predict the output.
Challenge
static string Shout(string s, int times = 2) => string.Concat(Enumerable.Repeat(s.ToUpper() + "!", times));
Console.WriteLine(Shout("go"));
Console.WriteLine(Shout("win", 3));Knowledge Check Quiz
- What prints?
- What does a default parameter do?
- What does void mean?