Monday, August 13, 2012

Method Parameters in C#

Functions or methods are heart of programming language. While crafting your application you will be requiring defining your custom methods now and then. Understanding methods, its parameters and return types are very important. C# provides some keyword like "out", "ref" or "params" to control your method parameters. These are called parameter modifiers. After getting so many phone calls on the same topic, I decided to write a blog on this.

To justify this I developed a project with some sample codes, if you want to download and experiment with that, ping me at facebook.

Before starting describing program sample, I made a small table to give you an idea about the latest (after C/C++ arena) keywords you can use in your method parameters.


Keyword  
Description
If nothing is mentioned

Signifies Pass by Value. Called method receives the exact copy of the data being passed
Keyword: “ref” before data type
Initially assigned by the caller; optionally reassigned by called method. Pass by Reference


Keyword: “out” before data type
This is also pass by reference. As the name indicates, output parameters must be assigned by method being called. Unlike ref, it will throw an error otherwise
Keyword: “params”
Variable number of arguments can be send with this keyword. A word of caution, only a single params modifier can be taken for a method.



             Now, let us see one by one. First, let us consider, pass by value.

If Nothing is mentioned


    Consider I have the following function. I took a basic console application where Program is the class name and entry point Main is static. All the functions I wrote within the class itself. It is advised that you make the necessary changes when you use these feature for other type of application.  
    

     static int Add2Numbers(int FirstValue, int SecondValue)
        { 
           return (FirstValue+SecondValue);
        }

    At the time of calling the method what we do is mentioned below

            int firstNo = 4;
            int secondNo = 5;

            Console.Write("\n\tAddition Result: {0}", Add2Numbers(firstNo, secondNo));
            Console.ReadKey();

   That is it. Now, consider if I change the Add2Numbers method to something like following

    static int Add2Numbers(int FirstValue, int SecondValue)
        { 
              int AddResult = FirstValue+SecondValue;
            
               FirstValue = 10;
               SecondValue = 20; 
             return (AddResult);
        }

   Nothing will happen to the variables in main function. This is pass by value. Let's move ahead with other modifier as mentioned in the table.

Using ref method parameter modifier

       In some situation you might be requiring to leave the control to the method and do not want a single value to be returned back. Called method will get the control to modify and return back a set of values. See the live example, to clarify your concept

     static void SwapValues(ref string FirstValue, ref string SecondValue)
        {
            FirstValue = "I Love My Country";
            SecondValue = " India";

        }

    Now, if the main method has the following:


            string FirstString = "Information", SecondString = "Handler";
            Console.Write("\n\n\t Initial Values in FirstString and SecondString room respectively: {0},{1}", FirstString, SecondString);

            //Call the method with "ref" parameter modifier
            SwapValues(ref FirstString, ref SecondString);

            Console.Write("\n\n\t After Calling the Method values in  FirstString  and  SecondString  room respectively: {0},{1}", FirstString, SecondString);

            Console.ReadKey();

  What will happen? It will display "I Love My Country India". This is what is the concept behind Pass by reference. 

Using "out" parameter modifier

     Methods which take out parameters are bound to assign values within method body. To understand this consider the following method body.

      static void Add2Numbers(int FirstValue, int SecondValue, out int AddResult)
        {
            AddResult=FirstValue + SecondValue;
        }  

      See here compulsorily, the method assigned a value. Notice the syntactical part of it as well. No need to return the value after addition. This is also pass by value.
     
      Now, the question is how main method will access it? Note the following code sample



            int firstNo = 4;
            int secondNo = 5;
           
           //No need to assign
            int addResult;

            Add2Numbers(firstNo, secondNo, out addResult);
            // Just use the addResult variable
            Console.Write("\n\tAddition Result: With out Param {0}", addResult);
            Console.ReadKey();

      Seems similar to ref modifier. Isn't it? Is there any other special purpose of out modifier? Good questions. Let me discuss a special purpose to give you a comprehensive idea about "out".

      One tempting feature of out is that you can return multiple values from a single method. Isn't it tempting? Lets move ahead to see a demonstration. Consider the following method body:

  
    static void MultipleReturnValueTest(out int ANumeric, out string AString, out bool TrueFalseBrother)
        {
            ANumeric = 999;
            AString = "Information Management is all about....";
            TrueFalseBrother = true;
        }


Now, the code segment which a calling function can have. Consider the following:


            int BogusNo; string BogusString; bool BogusTestVariable;

            MultipleReturnValueTest(out BogusNo, out BogusString, out BogusTestVariable);

            Console.Write("\n\\ntReally Enjoyed out Params....................");
            Console.Write("\n\t*********************************************");
            Console.Write("\n\n\tInteger With out Param {0}", BogusNo);
            Console.Write("\n\n\t String: With out Param {0}", BogusString);
            Console.Write("\n\n\t Bool: With out Param {0}", BogusTestVariable);

            Console.ReadKey();


         Pretty interesting if you used C/C++. I found this most interesting. I expect your views on the comment on this.



 Using "params" modifier

   This is one of the most important modifier. Feeling excited to inform you that you can pass variable number of parameters in a method. The called method consider the parameter(s) as a single logical one. Do you require this at all? Think, a set of number (number of values are not defined) will be input and the method will return sum of the series. Very exciting. Consider the following function:

      static int SumOfSeries(params int[] SetOfValues)
        {
            Console.Write("\n\n\tNumber of Params passed by User:{0}",SetOfValues.Length);
            
            int Sum=0;
            if (SetOfValues.Length == 0)
            {
                return Sum;
            }
            else
            {
                for (int k = 0; k < SetOfValues.Length; k++)
                    Sum += SetOfValues[k];
            }
            return Sum;
        }

    See, the syntactical part of it as well. Now, how can I call from main or other functions? Well, follow the following code fragment:

           //First way of calling the function
            int sumofSeries = SumOfSeries(2, 2, 3, 4, 5,6);
            Console.Write("\n\n\tSum of the Series Specified: {0}", sumofSeries);
            Console.ReadKey();

            //Pretty Interesting? Is there anything else? .

            int[] MyValueSet = { 1, 2, 3, 4, 5 };


            Console.Write("\n\n\tSum of the Array Specified: {0}", SumOfSeries(MyValueSet));
            Console.ReadKey();


  So, there are two ways to you can call them. The ways are either call the method directly with list of values or store in one array variable. 

  This article aimed to give you a overview of the method parameter modifiers and its understanding. If, you feel this helpful put comments below. If not, let me know. 

6 comments:

  1. Nice article.

    one more things if added then it will be nice is that: whenever multiple parameter is in method along with param feature then param parameter MUST BE LAST parameter.

    very conceptual with practical code.

    ReplyDelete
  2. if you were using magix, http://code.google.com/p/magix-illuminate-2 - you wouldn't have to differentiate between input and return parameters, having as many of each as you wish, in all "methods", due to the active event design pattern. interesting writeup though :)

    ReplyDelete