Methods & Parameters
Methods are reusable, modular code blocks. C# provides parameter modifiers like ref, out, and params to control how variables are passed.
1 Parameter Modifiers: out, ref, and params
C# parameter modifiers extend standard pass-by-value behaviors:
- ref: Passes a variable by reference. The variable must be initialized before it is passed to the method.
- out: Used to return multiple values from a method. The variable does not need to be initialized before it is passed, but the method **must assign a value** to it before returning.
- params: Allows a method to accept a variable number of arguments of the same type, bundling them into an array dynamically.
2 Parameter Modifiers Code
Let's run a program illustrating methods, overloading, and C# parameter modifiers:
C# — Methods
▶ Run Code
using System;
class Program {
// 1. ref parameter (modifies the caller's variable)
static void DoubleValue(ref int x) {
x *= 2;
}
// 2. out parameter (returns output values)
static void CalculateArea(int radius, out double area) {
area = Math.PI * radius * radius;
}
// 3. params array
static int SumValues(params int[] numbers) {
int sum = 0;
foreach (int n in numbers) sum += n;
return sum;
}
static void Main() {
int score = 50;
DoubleValue(ref score);
Console.WriteLine("After ref double: " + score);
CalculateArea(5, out double calculatedArea);
Console.WriteLine("Area via out: " + calculatedArea);
Console.WriteLine("Sum via params: " + SumValues(1, 2, 3, 4, 5));
}
}
3 Code Challenge
Challenge: Write a method called `Divide` that takes two integers and uses an `out` parameter to return the remainder of the division. Call the method and print both the quotient and the remainder.