C# Method Parameters
Pass data to methods for flexible functionality
๐ฅ What are Method Parameters?
Parameters allow you to pass information into methods, making them flexible and reusable. They act as variables that receive values when the method is called, enabling dynamic behavior based on input.
// Method with parameter
static void Greet(string name)
{
Console.WriteLine("Hello, " + name + "!");
}
Greet("Alice"); // Output: Hello, Alice!
Parameter Concepts
Parameters
Variables in method definition
void Print(string text)
{
// text is parameter
}
Arguments
Actual values passed to method
Print("Hello");
// "Hello" is argument
Multiple Parameters
Pass several values at once
int Add(int a, int b)
{
return a + b;
}
Default Values
Optional parameters with defaults
void Greet(string name = "Guest")
{
// name defaults to "Guest"
}
๐น Single Parameter
A single parameter method accepts one argument, which acts as an input variable inside the method body. For example, void Display(string message) uses message to output text. This is the simplest form of parameter passing, ideal for operations that require a single piece of data. It keeps method calls clean and focused. Ensure the parameter name is descriptive to convey its purpose, improving code clarity and making the method's intent immediately obvious to other developers.
class Program
{
// Method with one parameter
static void PrintMessage(string message)
{
Console.WriteLine("Message: " + message);
}
static void Square(int number)
{
int result = number * number;
Console.WriteLine(number + " squared is " + result);
}
static void Main(string[] args)
{
// Call methods with arguments
PrintMessage("Hello World");
PrintMessage("C# is fun!");
Square(5);
Square(10);
}
}
// Output:
// Message: Hello World
// Message: C# is fun!
// 5 squared is 25
// 10 squared is 100
Output:
Message: Hello World Message: C# is fun! 5 squared is 25 10 squared is 100
๐น Multiple Parameters
Methods with multiple parameters accept several inputs, enabling more complex and flexible operations. Parameters are defined in a comma-separated list, and arguments must be provided in the same order. For instance, void Register(string name, int age, bool isActive) collects user details. This allows methods to handle richer data sets. Always consider the parameter order carefully, as it affects usabilityโor use named arguments to improve readability and reduce errors when calling the method with many parameters.
class Program
{
// Method with multiple parameters
static void DisplayPerson(string name, int age, string city)
{
Console.WriteLine("Name: " + name);
Console.WriteLine("Age: " + age);
Console.WriteLine("City: " + city);
Console.WriteLine("---");
}
static int Add(int a, int b)
{
return a + b;
}
static void Main(string[] args)
{
// Pass multiple arguments
DisplayPerson("Alice", 25, "New York");
DisplayPerson("Bob", 30, "London");
int sum = Add(15, 20);
Console.WriteLine("Sum: " + sum);
}
}
// Output:
// Name: Alice
// Age: 25
// City: New York
// ---
// Name: Bob
// Age: 30
// City: London
// ---
// Sum: 35
Output:
Name: Alice Age: 25 City: New York --- Name: Bob Age: 30 City: London --- Sum: 35
๐น Default Parameters
Default parameters allow you to assign predefined values, making arguments optional when calling a method. For example, void Log(string message, bool urgent = false) can be called with just the message. If the caller doesn't provide a value for urgent, it defaults to false. Default parameters must appear after all required parameters. This feature simplifies method calls, reduces the need for overloads, and provides sensible defaults, enhancing API convenience and backward compatibility.
class Program
{
// Method with default parameters
static void Greet(string name = "Guest", string greeting = "Hello")
{
Console.WriteLine(greeting + ", " + name + "!");
}
static int Multiply(int a, int b = 2)
{
return a * b;
}
static void Main(string[] args)
{
// Use default values
Greet(); // Uses both defaults
// Override first default
Greet("Alice"); // Uses default greeting
// Override both defaults
Greet("Bob", "Hi");
// Default parameter examples
Console.WriteLine("5 * default: " + Multiply(5));
Console.WriteLine("5 * 3: " + Multiply(5, 3));
}
}
// Output:
// Hello, Guest!
// Hello, Alice!
// Hi, Bob!
// 5 * default: 10
// 5 * 3: 15
Output:
Hello, Guest! Hello, Alice! Hi, Bob! 5 * default: 10 5 * 3: 15
๐น Named Arguments
Named arguments improve code clarity by letting you specify parameter names during method calls, independent of order. Instead of Print("John", 30), you can write Print(age: 30, name: "John"). This eliminates confusion when methods have many parameters or similar types. Named arguments are especially useful with optional parameters, allowing you to skip some defaults while specifying others explicitly. They make code self-documenting and reduce errors related to argument position.
class Program
{
static void CreateAccount(string username, string email, int age)
{
Console.WriteLine("Username: " + username);
Console.WriteLine("Email: " + email);
Console.WriteLine("Age: " + age);
Console.WriteLine("---");
}
static void Main(string[] args)
{
// Normal order
CreateAccount("john_doe", "[email protected]", 25);
// Named arguments - any order
CreateAccount(
age: 30,
username: "jane_smith",
email: "[email protected]"
);
// Mix of positional and named
CreateAccount("bob", email: "[email protected]", age: 28);
}
}
// Output:
// Username: john_doe
// Email: [email protected]
// Age: 25
// ---
// Username: jane_smith
// Email: [email protected]
// Age: 30
// ---
// Username: bob
// Email: [email protected]
// Age: 28
// ---
Output:
Username: john_doe Email: [email protected] Age: 25 --- Username: jane_smith Email: [email protected] Age: 30 --- Username: bob Email: [email protected] Age: 28 ---
๐น Return with Parameters
Methods can both accept parameters and return values, combining input flexibility with output capability. For example, int Multiply(int a, int b) { return a * b; } takes two numbers and returns their product. This pattern is fundamental for calculations, data transformations, and reusable logic. The return type must match the declared type, and the method should have a clear, single responsibility. Such methods are highly testable and modular, forming the building blocks of maintainable, functional code.
class Program
{
static int CalculateArea(int length, int width)
{
return length * width;
}
static double CalculateAverage(int num1, int num2, int num3)
{
int sum = num1 + num2 + num3;
return (double)sum / 3;
}
static string GetFullName(string firstName, string lastName)
{
return firstName + " " + lastName;
}
static void Main(string[] args)
{
int area = CalculateArea(5, 10);
Console.WriteLine("Area: " + area);
double avg = CalculateAverage(80, 90, 85);
Console.WriteLine("Average: " + avg);
string fullName = GetFullName("John", "Doe");
Console.WriteLine("Full Name: " + fullName);
}
}
// Output:
// Area: 50
// Average: 85
// Full Name: John Doe
Output:
Area: 50 Average: 85 Full Name: John Doe
๐น Parameter Best Practices
Follow best practices for parameters: keep the number reasonable (under 3-4), use descriptive names, and prefer immutability. Avoid "out" and "ref" parameters when possible, as they can reduce clarity. Validate input parameters early to fail fast and prevent errors. Use optional and named arguments to improve usability. Consistent parameter ordering across related methods enhances predictability. These guidelines lead to clean, robust, and developer-friendly APIs that are easier to debug, test, and maintain over time.
Best Practices:
- Descriptive names: Use clear parameter names (age, not a)
- Order matters: Required parameters first, optional parameters last
- Limit count: Too many parameters (>5) can be confusing
- Type safety: Use appropriate data types for parameters
- Validation: Check parameter values when necessary
๐น Practical Example: Grade Calculator
A grade calculator method demonstrates effective parameter usage by computing letter grades from scores. For example, string CalculateGrade(double score, bool isExtraCredit = false) adjusts the score if extra credit applies, then returns "A", "B", etc. This method uses optional parameters for flexibility and returns a meaningful result. It shows how parameters enable customization (like extra credit) while keeping the interface simple. Such practical examples highlight how well-designed parameters create intuitive, reusable business logic.
class Program
{
static double CalculateGrade(int score1, int score2, int score3)
{
return (score1 + score2 + score3) / 3.0;
}
static string GetLetterGrade(double average)
{
if (average >= 90) return "A";
else if (average >= 80) return "B";
else if (average >= 70) return "C";
else if (average >= 60) return "D";
else return "F";
}
static void DisplayReport(string name, double average, string letter)
{
Console.WriteLine("Student: " + name);
Console.WriteLine("Average: " + average);
Console.WriteLine("Grade: " + letter);
Console.WriteLine("---");
}
static void Main(string[] args)
{
double avg = CalculateGrade(85, 92, 88);
string grade = GetLetterGrade(avg);
DisplayReport("Alice", avg, grade);
}
}
// Output:
// Student: Alice
// Average: 88.33333333333333
// Grade: B
// ---
Output:
Student: Alice Average: 88.33333333333333 Grade: B ---