CHASH Tutorial



C# METHOD PARAMETERS


C# Method Parameters

Method parameters allow you to pass values or variables into methods so they can use the data to perform operations.

Types of Parameters in C#

  • Value Parameters (default)
  • Reference Parameters (ref)
  • Output Parameters (out)
  • Optional Parameters
  • Params Keyword (Variable number of arguments)

1. Value Parameters

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

2. Reference Parameters (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

3. Output Parameters (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}");
}
  

4. Optional Parameters

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
}
  

5. Params Keyword (Variable Number of Arguments)

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


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review