Methods and One of Its Best Buddy Parameters - CodeProject

:

While discussing few concepts at my workplace, a point came up and caught my attention. How many ways could one pass value as a parameter in a method and how can we play with it and make it useful. Well, in my 4 years of developer life, I used 3 ways to pass the parameters and apart from that, I was unaware about others as I was comfortable using those methods as it fulfills my requirement.

So in this tip, let's begin with the basic one where I want a single value from function. I can do that easily by making my function return something in the below example. In this example, I have created a function that returns integer value.

private static int Sum(int first, int second)
{
   return first + second;
}
static void Main(string[] args)
{
   int value=Sum(2, 4);
   Console.Write("Sum of the two number: {0} ", value.ToString());
   Console.ReadKey();
}

Now what if I need two values from a single function, but the problem is that I can get a single value which my function returns. For that in C#, we have “ref” keyword.

static void Main(string[] args)
{
   int value = 0;
   int multiplication= MultiplyAndSumUsingRef(2, 4, ref value);
   Console.Write("Sum and multiplication of the two numbers are : {0},{1} ", 
			value.ToString(),multiplication .ToString());
   Console.ReadKey(); 
} 
private static int MultiplyAndSumUsingRef(int first, int second, ref int output)
{
   output= first + second;
   return first * second;
}

Here, I have used ref keyword which assigns the value in my output variable that I passed as a parameter. I can have multiple ref type parameters.

Now, we have one other type of methods parameter “out”. The usage of this parameter is quite different but the objective is the same, get the value for a variable in a calling function.

static void Main(string[] args)
{
   int value ;
   int multiplication = SumAndMultiply(2, 4, out value);
   Console.Write("Sum and multiplication of the two numbers are : {0},{1} ", 
			value.ToString(),multiplication.ToString());
  Console.ReadKey(); 
}
private static int SumAndMultiply(int first, int second, out int output)
{
   output = first + second;
   return first * second;
}

Like ref, we can set multiple out type parameters.

Well, the difference between ref and out is that in ref it is mandatory to assign the value before passing as argument and it's not necessary that one should set the value in called function. If I just declare the variable int value and not assign the value, the code won't compile.

static void Main(string[] args)
{
  int value ;
  int multiplication= MultiplyAndSumUsingRef(2, 4, ref value);
  Console.Write("Sum and multiplication of the two numbers are : {0},{1} ", 
		value.ToString(),mulitplication.ToString());
  Console.ReadKey(); 
}

In case of out, it is mandatory to set the value of out parameter in the called function.

private static int SumAndMultiply(int first, int second, out int output)
{
   return first * second;
}

This won't compile as its already mentioned above that the out parameter is not set in called function.

Note: ref and out have different behavior at run time, they are not considered as part of methods during compile time and they can't be overloaded as one is “ref” argument and other is out argument.

Now, what I am going to mention is different from the topic, but related to methods. Sometimes, we create a function like:

private static int MyFunction(int a, int b)
{
  return a + b;
}

and used in my whole application in different pages.

And suddenly at one page from where I am calling this function, I need to pass one more variable, so what option do I have left.

  1. To make one more function
  2. Add one more optional parameter and set the default value like:
private static int MyFunction(int a, int b, int c=0)
{
   return a + b + c;
}

This won't affect my logic and I don't need to change that function in every page. But keep it in mind that your optional parameter should be in last. We can have multiple optional parameters.

private static int MyFunction(int a, int b, int c=0, int d )
{
   return a + b + c;
}

You will get this error:

"Optional parameters must appear after all required parameters"

Another type we have “params”. In this, we pass the array of argument of specified type.

private static void TestParams(params int[] paramList)
{
  Console.WriteLine("the value in the parameter list are ");
   for (var revValue = 0; revValue < paramList.Length; revValue++)
   {
      Console.WriteLine(paramList[revValue]);
   }
   Console.ReadKey(); 
}
static void Main(string[] args)
{
  TestParams(1, 3, 4, 6, 7);
}

As in the example, I pass the array of integer type as argument.

I can also pass an array of object type so that I can also have the collection of different type like integer string and so on.

And when I call TestParams(); from Main function, then it won't throw any error in function TestParams as the array's length will be zero.

Note: params must be the last parameter, any parameter after that won't be allowed. It will throw compile time error. We can have a parameter before params type like int, string and so on.

A little exercise for the readers, which declarations are correct:

TestParams(params int[] paramList,params string[] paramList2 ){}
TestParams(int a ,params int[] paramList ){}
TestParams(int a ,int b,params int[] paramList ){}
TestParams(int a ,int b,params int[] paramList, int c ){}

Tuple

Now, the last thing that I will cover in this blog is Tuple.

Well, before going to code, Tuple is a class and can be used in places where we want multiple values from a function without using “out” or “ref” type parameters.

A Tuple is an immutable (unable to change) so once created, it can't be changed so can be reused.

Example:

private static Tuple<int, string, int, string,bool> TestTuple()

{
  var myTuple= new Tuple<int,string ,int ,string,bool>(1,"Hello!",2,"Are you Developer?",true);
  return myTuple;
}
static void Main(string[] args)
{
  var tupleResult = TestTuple();
  Console.Write("She said two things {0}. {1} and {2}. {3} and when I said {4} she said awesome", 
	tupleResult.Item1, tupleResult.Item2, tupleResult.Item3, tupleResult.Item4, tupleResult.Item5);
  Console.ReadKey(); 
}

Another way to create a Tuple is by using Create method.

Tuple.Create("I", "am", "another", "approach", "to create", "tuple");

In Tuple, we can also have arrays, List and so on.

To know more about Tuple, you can visit this link.

I hope this was not a waste of your time. :)

Happy coding!