Learn C# · lesson 23 of 61 · about 8 minutes
Parameters and Return Values
Show each fighter's HP with a method that takes values as parameters, hands text back with return, and has an optional parameter.
What you'll learn
- Declare parameters
- Return a value
- Use optional and named arguments
A status line
A status line like Ada: 22/100 HP is useful for every fighter, so it deserves a method. Status(string name, int hp, int max = 100) takes the name and HP as parameters and hands the finished text back with return. Most fighters have at most 100 HP, so max has a default; the Slime only ever has 12, which the call gives with a named argument, max: 12.
In and out
- Parameters are typed inputs:
static int Square(int n) returnsends a value back and ends the method; the type before the name says what comes back- An optional parameter has a default:
static string Greet(string name, string greeting = "Hello") - A named argument says which parameter it's for:
Greet("Bo", greeting: "Hey") - A one-line method can use
=>:static int Square(int n) => n * n;
Giving a value back
Console.WriteLine(Triple(5));
static int Triple(int n)
{
return n * 3;
}Output
15Step through a call: into the method and back
int a = Square(3);
Console.WriteLine(a + 1);
static int Square(int x)
{
return x * x;
}Output
10Returning values
int area = Area(4, 5);
Console.WriteLine($"Area {area}, square {Square(area)}");
Console.WriteLine(Greet("Ada"));
Console.WriteLine(Greet("Bo", greeting: "Hey"));
static int Area(int width, int height)
{
return width * height;
}
static int Square(int n) => n * n;
static string Greet(string name, string greeting = "Hello") => $"{greeting}, {name}!";Output
Area 20, square 400
Hello, Ada!
Hey, Bo!Now try it yourself
This lesson is free in Codiqo, with 11 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.