Method parameters allow you to pass values or variables into methods so they can use the data to perform operations.
By default, parameters are passed by value, meaning the method gets a copy of the data.
static void DoubleValue(int num)
{
num = num * 2;
Console.WriteLine("Inside method: " + num);
}
static void Main()
{
int number = 10;
DoubleValue(number);
Console.WriteLine("Outside method: " + number);
}
Output:
Inside method: 20 Outside method: 10
ref
)Pass parameter by reference so changes inside the method affect the original variable.
static void DoubleRef(ref int num)
{
num = num * 2;
Console.WriteLine("Inside method: " + num);
}
static void Main()
{
int number = 10;
DoubleRef(ref number);
Console.WriteLine("Outside method: " + number);
}
Output:
Inside method: 20 Outside method: 20
out
)Used to return multiple values from a method. The variable must be assigned inside the method before returning.
static void GetValues(out int a, out int b)
{
a = 5;
b = 10;
}
static void Main()
{
int x, y;
GetValues(out x, out y);
Console.WriteLine($"x = {x}, y = {y}");
}
Parameters that have default values. Caller can omit them.
static void Greet(string name = "Guest")
{
Console.WriteLine("Hello, " + name);
}
static void Main()
{
Greet(); // Hello, Guest
Greet("Technorank"); // Hello, Technorank
}
Allows passing a variable number of arguments as an array.
static void PrintNumbers(params int[] numbers)
{
foreach (int num in numbers)
Console.Write(num + " ");
Console.WriteLine();
}
static void Main()
{
PrintNumbers(1, 2, 3);
PrintNumbers(10, 20);
}
Output: 1 2 3
10 20
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!