In C#, methods (often called functions) are blocks of code that perform specific tasks. To make methods versatile and reusable, you can pass data into them. This data is passed using Parameters and Arguments.
Understanding how data flows into and out of methods is crucial for writing clean, modular, and maintainable C# code.
While often used interchangeably, there is a distinct technical difference between the two terms:
// 'name' is the Parameter
public void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}
// "Alice" is the Argument
Greet("Alice");
C# supports several ways to pass arguments to methods:
ref and out): A reference to the memory location is passed. Changes made inside the method do affect the original variable.params): Allows passing a dynamic number of arguments.By default, value types (like int, double, bool, structs) are passed by value. The method receives a duplicate copy.
public class Program
{
public static void Main()
{
int originalNumber = 10;
Console.WriteLine($"Before method: {originalNumber}");
ModifyNumber(originalNumber);
// The original variable remains unchanged!
Console.WriteLine($"After method: {originalNumber}");
}
public static void ModifyNumber(int num)
{
num = num * 2;
Console.WriteLine($"Inside method: {num}");
}
}
Before method: 10 Inside method: 20 After method: 10
refIf you want the method to permanently modify the original variable passed in, you use the ref keyword. The variable must be initialized before being passed as an argument.
public class Program
{
public static void Main()
{
int score = 50;
Console.WriteLine($"Before method: {score}");
// You must include the 'ref' keyword when calling the method
AddBonus(ref score);
Console.WriteLine($"After method: {score}");
}
// You must include the 'ref' keyword in the parameter list
public static void AddBonus(ref int currentScore)
{
currentScore += 100;
}
}
Before method: 50 After method: 150
out KeywordThe out modifier is similar to ref, but it doesn't require the variable to be initialized before it is passed. However, the method must assign a value to the out parameter before it exits. It is heavily used to return multiple values from a single method.
public class Program
{
public static void Main()
{
// Notice we don't initialize these variables
int sum;
int product;
Calculate(5, 4, out sum, out product);
Console.WriteLine($"Sum: {sum}, Product: {product}");
}
public static void Calculate(int a, int b, out int addResult, out int multResult)
{
addResult = a + b;
multResult = a * b;
// The method will not compile if addResult or multResult are left unassigned.
}
}
Sum: 9, Product: 20
You can provide default values for parameters, making them optional. When calling the method, you can use Named Arguments to skip certain optional parameters while providing others.
public class Program
{
public static void Main()
{
// Using all default values
CreateProfile("JohnDoe");
// Providing arguments sequentially
CreateProfile("JaneDoe", 25, "Canada");
// Using Named Arguments to skip 'age' but provide 'country'
CreateProfile("Alex", country: "UK");
}
// 'age' and 'country' are optional parameters
public static void CreateProfile(string username, int age = 18, string country = "USA")
{
Console.WriteLine($"User: {username}, Age: {age}, Country: {country}");
}
}
User: JohnDoe, Age: 18, Country: USA User: JaneDoe, Age: 25, Country: Canada User: Alex, Age: 18, Country: UK
params KeywordThe params keyword allows a method to accept a variable number of arguments of the same type. It must be the last parameter in the method signature.
public class Program
{
public static void Main()
{
PrintShoppingList("Apples", "Bananas", "Milk", "Bread");
PrintShoppingList("Eggs");
}
// Accepts any number of strings
public static void PrintShoppingList(params string[] items)
{
Console.WriteLine("--- Shopping List ---");
foreach (string item in items)
{
Console.WriteLine("- " + item);
}
}
}
--- Shopping List --- - Apples - Bananas - Milk - Bread --- Shopping List --- - Eggs
Mastering method parameters allows you to write highly flexible code. Now that you understand ref, out, and params, you can dive into more advanced C# features such as Method Overloading, where you define multiple methods with the same name but entirely different parameter signatures!