(C# Language) Methods and ref, in, params and Named Args

Functions in C# are usually called Methods. They can exist inside a class, struct, record - but not globally outside. So every function, including the Main function must be declared inside a class or a struct. In this tutorial we examine default arguments, named arguments, passing parameters by value and reference, the use of in keyword and finally passing unspecified number of arguments with the params keyword.
(Rev. 30-Sep-2022)

Categories | About |     |  

Parveen,

The Syntax of a Method

Consider this program where we have a method called sum that takes four numbers. The default value of the third parameter is 15 if it is un-specified at the time of call. The default value of the last parameter has been indirectly specified by using the default keyword. This keyword automatically substitutes a 0 because the default value of int data type is 0.

The code in the function calculates the sum into a variable. Then it uses the return statement to return it to the caller.


namespace ConsoleApp1
{
  class Program
  {
    // instance function with the  
    // last two parameters defaulted 
    public int sum (
        int num1, int num2, 
        int num3 = 15, int num4 = default )
    {
      int total = num1 + num2 + num3 + num4;

      return total;

    }

    static void Main()
    {
      var p = new Program();

      int ret = p.sum(num2: 4, num1: 2, num4: 5);

      Console.WriteLine($"Sum = {ret}");

    }
  }
}

The function has been marked public. This function is an instance function because it hasn't been marked with the static keyword. This behaviour is same as in C++ and Java.

Next we have the main function. Create an instance of the class with the new keyword. The sum function has been called by using the concept of named arguments. The second, first and fourth arguments have been passed by using the names of the parameters as they appear in the function declaration. The order is not important because we have used the names of the parameters.

lastly, we can print the sum.

Video Explanation (see it happen!)

Please watch the following youtube video:

Pass by Reference and Value

ValueType arguments can be passed by reference and value in the same manner as in C++.

The argument must be a value type.

Consider this function that has two parameters of int type; recall that int is a value type. The first parameter gets a copy of its argument because value-types are passed by value. The second parameter has been marked with ref keyword. This means that the parameter will be passed by reference.

Inside the body we increment both the arguments.


class Program
{
  static void fx(int p1, ref int p2)
  {
    p1++;

    p2++;

  }

  static void Main()
  {
    int i = 3, j = 4;

    Program.fx(i, ref j);

    Console.WriteLine($"after call: i = {i}, j = {j}");

    // prints i = 3, j = 5 

  }
}

Next we have the main function, where we create two int type of variables i and j. These variables are passed to the function. The function is a static function, so we have called it by using the name of the class. The variable i is passed by copy, and the variabe j is passed by reference. The ref keyword is required at the time of calling this function.

Finally the variables are printed after the function call. We expect i to remain unchanged because it was passed by value, and we expect j to have been incremented because it was passed by reference.

Pass by const Reference using the "in" keyword

If you are from C++ background then you must be familiar with const ref& style of passing arguments by reference and yet ensuring that the caller doesn't modify the data contained in the variable. The same behavior is possible in C# as well.


// pass by ref and value 
static void fx(int p1, in int p2)
{
  p1++;

  // compiler error here because  
  // p2 cannot be modified 
  p2++;

}

We have to use the in keyword instead of the ref keyword. We have two parameters - the first one is passed as a value, whereas the second has now been passed by using the in keyword - which means that it would be passed as a constant reference.

The compiler allows us to modify the first parameter, but generates an error if we try to modify the second value.

This is how the in keyword works.

params keyword

Consider this program where we have a function called Adder that accepts an un-specified count of int numbers as a parameter array.


// use params keyword for  
// un-specified count of arguments 

static int Adder(params int[] numbers)
{

  if (null == numbers)
    return 0;

  int sum = 0;

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

  return sum;

}

static void Main()
{
  int ret = Program.Adder(7, 9, 5);

  Console.WriteLine($"sum = {ret}");

  // alternate  
  int ret2 = Program.Adder(new[] {7, 9, 5 });

}


First a null-check is made.

Then a variable for storing the sum is created. After that a foreach loop is used to add the numbers. Notice that this function is capable of receiving any count of numbers.

Next we have the main function. The Adder function is called by passing three numbers and the sum stored in a variable.

Finally, the sum is printed using the console writeline function.

We have also added a statement to show an alternate way of passing multiple arguments by using the new keyword in an array-like syntax.

We'll close now. Thanks!


This Blog Post/Article "(C# Language) Methods and ref, in, params and Named Args" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.