Method Parameter Modifiers in C#


Introduction

Usually methods takes parameters. There are many ways to pass the parameters and for this C# provides some parameter modifiers. Look at them below.

1. none (or default) parameter: If parameter is not attached with any modifier, then parameter’s value is passed to the method. This is also known as call-by-value and it is defualt to any parameter.

2. ref (reference) parameter: If parameter is attached with ref modifier, then changes will made in method affect the calling method. This is also known as call-by-reference.

3. out (output) parameter: If parameter is attached with out modifier, then we can return value to a calling method without using return statement.

4. params (parameters) parameter: If parameter is attached with params modifier, then we can send many numbers of arguments as a single parameter. Any method can have only one params modifier and it should be the last parameter for the method.

Let’s see all one by one by using in program.

C# Default Parameter

By default, the parameters are passed to a method by value. So, the changes made for parameters within a method will not affect the actual parameters of the calling method. Look at the following program which tries to swap the number and not success just because of call-by-value not affect the actual parameter.

    class Program
    {
        public static void swap(int x, int y)
        {
            int temp = x;
            x = y;
            y = temp;
        }
        static void Main()
        {
            int x = 10, y = 12;
            Console.WriteLine("Before: x={0}, y={1}", x, y);
            swap(x, y);
            Console.WriteLine("After: x={0}, y={1}", x, y);
            Console.ReadKey();
        }
    }

Output:
Before: x=10, y=12
After: x=10, y=12

Now, let’s swap by using ref (reference or call-by-reference) modifier.

C# ref Parameter

Whenever we want the changes made in method to get affected in the calling method, then we will go for call by ref. Following are the differences between output (out) and reference (ref) parameters:

1. The output (out) parameters do not need to be initialized before sending to called method. Because it is assumed that the called method will fill the value for such parameter.
2. The reference (ref) parameters must be initialized before sending to called method. Because, we are passing a reference to an existing type and if we don’t assign an initial value, it would be equivalent to working on NULL pointer.

Let’s have an program which swaps value:

    class Program
    {
        public static void swap(ref int x, ref int y)
        {
            int temp = x;
            x = y;
            y = temp;
        }
        static void Main()
        {
            int x = 10, y = 12;
            Console.WriteLine("Before: x={0}, y={1}", x, y);
            swap(ref x, ref y);
            Console.WriteLine("After: x={0}, y={1}", x, y);
            Console.ReadKey();
        }
    }

Output:
Before: x=10, y=12
After: x=12, y=10

Look at one another program.

    class Program
    {
        public static void MyFun(ref string s)
        {
            s = s.ToUpper();
        }
        static void Main()
        {
            string s = "abhimanyu";
            Console.WriteLine("Before: {0}", s);
            MyFun(ref s);
            Console.WriteLine("After: {0}", s);
            Console.ReadKey();
        }
    }

Output:
Before: abhimanyu
After: ABHIMANYU

C# out Parameter

In some of the methods, we need to return a value to a calling method. Instead of using return statement, for this C# provides a modifier for a parameter as out. The usage of out can be better understood by the following program.

    class Program
    {
        public static void add(int x, int y, out int z)
        {
            z = x + y;
        }
        static void Main()
        {
            int x = 10, y = 12, z;
            add(x, y, out z);
            Console.WriteLine("z={0}", z);
            Console.ReadKey();
        }
    }

Output:
z=22

The out parameter is certainly useful when we need more values to be returned from a method. Consider one more program.

    class Program
    {
        public static void CallFun(out int x, out string s)
        {
            x = 10;
            s = "My name is Abhimanyu.";
        }
        static void Main()
        {
            int x;
            string str;
            CallFun(out x, out str);
            Console.WriteLine("x={0}, str={1}", x,str);
            Console.ReadKey();
        }
    }

Output:
x=10, str=My name is Abhimanyu.

C# params Parameter

The params keyword of C# allows us to send many numbers of arguments as a single parameter. The usage of params can be better understood by the following program.

    class Program
    {
        public static void CallFun(params int[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                Console.Write(arr[i]);
                Console.Write(", ");
            }
        }
        static void Main()
        {
            int[] x = new int[4] {10, 12, 15, 17};
            int a = 20, b = 1988;
            CallFun(x);
            CallFun(a, b);
            Console.ReadKey();
        }
    }

Output:
10, 12, 15, 17, 20, 1988,

In the above program we can observe that for params parameter, we can pass an array or set of individual elements. We can use params even when the parameters to be passed are of different types, look at the program.

    class Program
    {
        public static void CallFun(params object[] arr)
        {
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i] is Int32)
                {
                    Console.WriteLine("{0} is an integer.", arr[i]);
                }
                if (arr[i] is string)
                {
                    Console.WriteLine("{0} is a string.", arr[i]);
                }
                if (arr[i] is bool)
                {
                    Console.WriteLine("{0} is a boolean.", arr[i]);
                }
            }
        }
        static void Main()
        {
            int x = 10;
            string s = "abhimanyu";
            bool b = true;
            CallFun(b,x,s);
            Console.ReadKey();
        }
    }

Output:
True is a boolean.
10 is an integer.
abhimanyu is a string.

So, that's all about the Method Parameter Modifiers in C#.
Thanks for reading

Comments

Popular posts from this blog

Customize User's Profile in ASP.NET Identity System

Lambda two tables and three tables inner join code samples