Labs ICT
Pro Login

Parameters and Return Values

Methods become truly powerful when they can accept input and produce output. Parameters are the inputs, and return values are the outputs. Let me show you how this works.

Parameters

Parameters are variables listed in the method declaration. They act as placeholders for the values you pass when calling the method:

void PrintMessage(string message, int times)
{
    for (int i = 0; i < times; i++)
    {
        Console.WriteLine(message);
    }
}

// Calling with arguments
PrintMessage("Hello!", 3);
PrintMessage("Let us learn C#", 2);

message and times are parameters. When you call the method, you pass actual values (called arguments) that get assigned to those parameters.

Return Values

A method can return a value using the return keyword. You specify the return type in the method declaration:

double CalculateArea(double length, double width)
{
    return length * width;
}

bool IsEven(int number)
{
    return number % 2 == 0;
}

string FormatCurrency(double amount)
{
    return $"₦{amount:N2}";
}

// Using them
double area = CalculateArea(5.0, 3.0);
Console.WriteLine(area);  // 15

Console.WriteLine(IsEven(4));  // True
Console.WriteLine(FormatCurrency(1500));  // ₦1,500.00

Default Parameters

You can give parameters default values so they are optional when calling the method:

void PrintInfo(string name, string city = "Unknown", int age = 0)
{
    Console.WriteLine($"{name}, {age} years old, from {city}");
}

// All arguments
PrintInfo("Bilal", "Kano", 25);

// Using defaults
PrintInfo("Fatima");              // Fatima, 0 years old, from Unknown
PrintInfo("Musa", age: 30);      // Musa, 30 years old, from Unknown

Parameters with default values must come after parameters without them. And when calling, you can use named arguments (like age: 30) to skip parameters in the middle.

Returning Multiple Values

Sometimes you need to return more than one value. C# has a few ways to do this:

// Using out parameters
void GetMinMax(int[] numbers, out int min, out int max)
{
    min = numbers.Min();
    max = numbers.Max();
}

int[] data = { 3, 7, 1, 9, 4 };
GetMinMax(data, out int minimum, out int maximum);
Console.WriteLine($"Min: {minimum}, Max: {maximum}");

// Using tuples (cleaner)
(int min, int max) GetMinMax2(int[] numbers)
{
    return (numbers.Min(), numbers.Max());
}

var result = GetMinMax2(data);
Console.WriteLine($"Min: {result.min}, Max: {result.max}");

Tuples are generally preferred in modern C# because they are cleaner and easier to use.