C# Method Parameters

Methods become truly powerful when they can accept and manipulate data dynamically.

In C#, this is achieved using method parameters. While basic parameters are straightforward, C# provides advanced parameter types like ref, out, params, and optional parameters to handle real-world scenarios efficiently.

Understanding these parameter types is essential for writing flexible, optimized, and production-ready code.


What are Method Parameters in C#?

Method parameters are variables defined in a method signature that receive values when the method is called.

Each parameter in C# must have a specific data type, which defines what kind of value it can accept.

public int Add(int a, int b)
{
    return a + b;
}

Here:

  • a is of type int (integer)
  • b is of type int (integer)
  • Both parameters can only accept integer values

This is known as type safety in C#.

If you try to pass a value of a different type, the program will throw a compile-time error.

// Invalid - passing string instead of int
Add("10", 20);

The above code will fail because "10" is a string, not an int.

Correct usage:

int result = Add(10, 20);

Here, 10 and 20 are called arguments, which match the expected parameter types.

This strict type checking helps prevent runtime errors and ensures better code reliability.


Value Type vs Reference Type Passing

By default, C# passes parameters by value.

public void ChangeValue(int num)
{
    num = 100;
}

This does not change the original variable because a copy is passed.

To modify the original value, C# provides ref and out parameters.


ref Parameter in C#

The ref keyword passes arguments by reference, meaning the method works on the original variable.

Key Rules

  • Variable must be initialized before passing
  • Both method and call must use ref
public void UpdateValue(ref int num)
{
    num = num + 10;
}

int value = 5;
UpdateValue(ref value);

Now value becomes 15.


out Parameter in C#

The out keyword is also used to pass parameters by reference, but it is mainly used for returning multiple values.

Key Rules

  • Variable does NOT need initialization before passing
  • Method MUST assign a value before returning
public void GetValues(out int a, out int b)
{
    a = 10;
    b = 20;
}

int x, y;
GetValues(out x, out y);

This allows methods to return multiple outputs.


ref vs out (Important Difference)

Feature ref out
Initialization Required Yes No
Must Assign Value Inside Method No Yes
Purpose Modify existing value Return multiple values

params Keyword in C#

The params keyword allows a method to accept a variable number of arguments.

Instead of passing an array explicitly, you can pass multiple values directly.

public int AddNumbers(params int[] numbers)
{
    int sum = 0;

    foreach(int num in numbers)
    {
        sum += num;
    }

    return sum;
}

Usage:

int result = AddNumbers(10, 20, 30, 40);

Key Rules

  • Only one params parameter is allowed
  • It must be the last parameter

Optional Parameters in C#

Optional parameters allow you to define default values for method parameters.

If no value is passed, the default value is used.

public void DisplayMessage(string message = "Hello User")
{
    Console.WriteLine(message);
}

Usage:

DisplayMessage();
DisplayMessage("Welcome!");

Key Rules

  • Optional parameters must come after required parameters
  • Default value must be constant

Named Parameters (Very Important)

C# allows passing arguments using parameter names, improving readability.

Add(b: 20, a: 10);

This removes dependency on parameter order.


Example 1 : Multiple Outputs

Using out for returning multiple values:

public void Calculate(int a, int b, out int sum, out int product)
{
    sum = a + b;
    product = a * b;
}

Example 2 : Flexible Inputs

Using params for dynamic number of values:

public double CalculateAverage(params int[] numbers)
{
    int total = 0;

    foreach(int num in numbers)
    {
        total += num;
    }

    return total / numbers.Length;
}

Common Mistakes

  • Forgetting to initialize variables when using ref
  • Not assigning values inside methods when using out
  • Using params incorrectly (not at last position)
  • Misplacing optional parameters before required ones

Best Practices

  • Use ref only when modification of original value is required
  • Use out for returning multiple results
  • Use params for flexible method inputs
  • Use optional parameters carefully to avoid confusion
  • Prefer clarity over clever usage

Summary

C# method parameters provide powerful ways to pass and manage data within methods.

Different parameter types like ref, out, params, and optional parameters allow developers to handle a wide range of real-world scenarios efficiently.

Choosing the right parameter type improves code flexibility, readability, and performance.

Understanding these concepts ensures better design and more maintainable applications.