Parameters and Return Values

How data moves in and out of your functions

Posted by Rodrigo Castro on November 3, 2024

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!