SIGN UP MEMBER LOGIN:    
ARTICLE

Method Parameter Modifiers in C#

Posted by Abhimanyu Kumar Vatsa Articles | C# Language July 21, 2011
In this quick article you will take a look at method parameter modifiers in C#.
Reader Level:

Introduction

Usually methods take 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 a parameter is not attached with any modifier, then the parameter's value is passed to the method. This is also known as call-by-value and it is the default for any parameter.

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

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

  4. params (parameters) parameter: If a parameter is attached with a params modifier, then we can send multiple 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 them in a 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 but does not succeed just because call-by-value does 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 a ref (reference or call-by-reference) modifier.

C# ref Parameter

Whenever we want to allow changes to be made in a method, then we will go for call by ref. The following are the differences between output (out) and reference (ref) parameters:

1. The output (out) parameters do not need to be initialized before use in a called method. Because it is assumed that the called method will provide the value for such a 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 a NULL pointer.

Let's have a program which swaps a 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 a 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 multiple 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 the 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.

HAVE A HAPPY CODING!!

Login to add your contents and source code to this article
share this article :
post comment
 

Also for beginners, note that members of reference types can be modified even if the reference type object is not passed with the "ref" modifier. The article could explain this but other articles and books and referrence types also explain it.

Posted by Sam Hobbs Jul 21, 2011

The reason why a return statement is not needed in any of the samples in this article is because the method has "void" and therefore does not return a value. If the function did have a return type (anything other than void) then it would need a return statement and the "out" modifier would be irrelevant to the need for a return statement. Also note that an "out" modifier does not JUST return a value; it allows an object to be returned that is created in the called method. So the statement that when an "out" parameter is used "it is assumed that the called method will provide the value" is misleading; it is more accurate to say that "it is assumed that the called method will create the object". The significance of that is that it explains that you do not need to use "new" for an object if the first thing that is done with it is to use it as an "out" parameter.

Posted by Sam Hobbs Jul 21, 2011

Hi Vatsa. Thanks for share ebook: http://ebook9000.com

Posted by hoabkit nguyen dang Jul 21, 2011

share ebook free: http://ebook9000.com

Posted by hoabkit nguyen dang Jul 21, 2011
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Nevron Gauge for SharePoint
Become a Sponsor