Understanding Method Parameter Modifiers in C#

C# language allows the use of certain modifiers with parameters of a method. Basically, these Method Parameter Modifiers effects the manner in which the corresponding method makes use of that parameter. In this post on Understanding Method Parameter Modifiers in C#, you will learn four of the parameter modifiers – ref, out, params, and in.

Method Parameter Modifiers

In this article, I will cover the following method parameter modifiers in C# language:

  • ref
  • out
  • params
  • in

ref Keyword

The ref keyword allows a parameter to be passed by reference. When you apply the ref keyword before any formal parameter in a method, then any change that you make in the value of that parameter will be reflected in the calling method also. Also, you need not return a ref parameter explicitly to the calling method.

Example:

using System;
namespace SwapUsingRef
{
    class Program
    {
        static void Main(string[] args)
        {
            int a, b;
            Console.WriteLine("Enter two numbers to swap: ");
            a = Int32.Parse(Console.ReadLine());
            b = Int32.Parse(Console.ReadLine());

            Console.WriteLine("Values Before Swapping: ");
            Console.WriteLine("a = " + a + " b = " + b);
            swap(ref a, ref b);
            Console.WriteLine("Values After Swapping: ");
            Console.WriteLine("a = " + a + " b = " + b);
        }
        static void swap(ref int a, ref int b)
        {
            a = a + b;
            b = a - b;
            a = a - b;
        }
    }
}

Output:

Demo of ref Parameters
Demo of ref Parameters

out Keyword

The out parameter is useful when you need to return several values from a method. When the out keyword is applied to a parameter, the method returns it automatically to the calling method. However, it is mandatory to assign a certain value to an out parameter inside the method.

Example:

using System;
namespace OutParameterDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int x, y, sum, difference, multiplication, division, remainder;
            Console.WriteLine("Enter two numbers for basic arithmetic operations: ");
            x = Int32.Parse(Console.ReadLine());
            y = Int32.Parse(Console.ReadLine());

            Compute(x, y, out sum, out difference, out multiplication, out division, out remainder);
            String str = "Sum= "+sum+"\nDifference: "+difference+"\nMultiplication: "+multiplication+"\nDivision: "+division+"\nRemainder: "+remainder;
            Console.WriteLine(str);
        }
        public static void Compute(int a, int b, out int sum, out int diff, out int multiply, out int divide, out int remainder)
        {
            sum = a + b;
            diff = a - b;
            multiply = a * b;
            if (b != 0)
                divide = a / b;
            else
            {
                Console.WriteLine("Divide by zero is not allowed! Division is not computed.");
                divide = 0;
            }
            if (b != 0)
                remainder = a % b;
            else
            {
                Console.WriteLine("Divide by zero is not allowed! Remainder is not computed.");
                remainder = 0;
            }
            
        }
    }
}

Output:

Demo of Out Parameters
Demo of Out Parameters
Understanding Method Parameter Modifiers in C#
Demo of Out Parameters

params Keyword

params keyword specifies that the parameter is a variable-size array. This parameter modifier is important when the method call may contain any number of values as parameters. However, in a method, you can use only one params array. Additionally, the params array when specified should be the last parameter in the formal parameter list of a method.

Example:

using System;
namespace ParamsKeywordDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            int n, s;
            n = CountOfElements(1, 2);
            Console.WriteLine("Count = " + n);

            n = CountOfElements(11, 2, 3, 4, 5);
            Console.WriteLine("Count = " + n);
            n = CountOfElements(6, 7, 8);
            Console.WriteLine("Count = " + n);
            n = CountOfElements(1,2,3,4,5,6,7,8,9,10);
            Console.WriteLine("Count = " + n);
            n = CountOfElements(10, 20, 30, 40);
            Console.WriteLine("Count = " + n);
            n = CountOfElements(100);
            Console.WriteLine("Count = " + n);

            Console.WriteLine("\nComputing Sum...");
            s = findSum(1, 2, 3);
            Console.WriteLine("sum=" + s);
            s = findSum(8);
            Console.WriteLine("sum=" + s);
            s = findSum(7, 9, 1, 2, 3, 4, 5);
            Console.WriteLine("sum=" + s);

            Console.WriteLine("\nIncrement and Sum Demo: ");
            int x, sum1;
            x = 5;
            sum1 = incrementAndSum(x, 2, 3, 5);
            Console.WriteLine("Incremented Sum: "+sum1);
            x = 2;
            sum1 = incrementAndSum(x, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
            Console.WriteLine("Incremented Sum: " + sum1);
        }
        // params keyword is used to specify a variable length array
        // size of params array depends upon the number of elements passed
        // since it is an array so all the values passed should be of same data type
        static int CountOfElements(params int[] arr)
        {
            return arr.Length;
        }
        static int findSum(params int[] arr1)
        {
            int sum = 0;
            for(int i=0;i<arr1.Length;i++)
            {
                sum += arr1[i];
            }
            return sum;
        }
        //We can pass other parameters along with the params array in a function
        //If we pass other parameters along with params array, then params array should be the last parameter
        // In other words, params array should be the right-most parameter
        //The following function will increment all the elements of params array by x and then computes the sum
        static int incrementAndSum(int x, params int[] arr2)
        {
            int sum = 0;
            for(int i=0;i<arr2.Length; i++)
            {
                arr2[i] += x;
                sum += arr2[i];
            }
            return sum;
        }
        //params array must be the last parameter in the function
        //Therefore we can't have more than one params array in the same function
        /*static void myfunction(int a, params int[] sarr, params int[] arr)
        {
        }*/
    }
}

Output:

Demo of params keyword
Demo of params keyword

in Keyword

The in parameter modifier also passes a parameter by reference as the ref keyword does. However, you cannot modify the in parameter inside the method. Basically, the use of in parameter is useful in situations when you don’t want that the corresponding method should make any changes in the parameter value.

Example:

using System;
namespace ConsoleApp17
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Sum = {0}", sum(12, 15));
        }
        public static int sum(in int x, in int y)
        {
         //   x++;
         //   y++;

            return x + y;
        }
    }
}

Output:

In Parameters Demo
In Parameters Demo

Important Points for Understanding Method Parameter Modifiers in C#

  1. We use the ref keyword for passing parameters by reference.
  2. The variable which we mark as ref should have some initial value before passing to the corresponding function.
  3. The out parameters return value to the calling function without the need for an explicit return statement.
  4. There is no need of initializing the out parameters before passing them in a function.
  5. The out parameters should be assigned some value in the method in which they are passed. otherwise, a compilation error occurs.
  6. A method should use only one params array and it should be the last parameter in the list of parameters.
  7. The in keyword makes a parameter readonly. In other words, any attempt to assign a value to an in parameter inside the body of the method results in a compilation error.

Related Topics

C# Basic Examples

Constructors in C#

C# Arrays

Leave a Comment

Your email address will not be published. Required fields are marked *