Functions can take inputs (parameters) and give you results (return values).
π₯ Parameters
Parameters let you pass data into a function.
1
2
3
4
5
void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}
Greet("Taylor"); // Hello, Taylor!
π€ Return Values
A function can return a value using the return
keyword.
1
2
3
4
5
int Square(int n)
{
return n * n;
}
int result = Square(5); // 25
π§βπ€βπ§ Multiple Parameters
You can have as many parameters as you need.
1
2
3
4
double Average(int a, int b, int c)
{
return (a + b + c) / 3.0;
}
π« No Return Value
If your function doesnβt return anything, use void
:
1
2
3
4
void PrintLine()
{
Console.WriteLine("This function returns nothing!");
}
π‘ Try It!
Write a function that takes a name and age, and prints a greeting:
1
2
3
4
void Greet(string name, int age)
{
Console.WriteLine($"Hello, {name}! You are {age} years old.");
}
Next: Static vs. instance methods!