Thursday, March 31, 2016

Method Parameters in C#

In today's blog post, I will be discussing method parameters in C#. We will see the different ways in which parameters can be passed to methods in C#.

Method Parameters

Other than regular way in which we assign values to method parameters, there are a few tweaks which we can do to make our relationships with methods more useful.



Let's look at them one by one.

Optional Parameters

For any method, if we want the parameter(s) to have a default value, we can simply assign it like this:

public int Calc(int min, int max, int range = 100)
{
     \\...
}

So if any calling code passes a value for range, then that value is used. If we say Method1(1, 20, 200), then 200 is used for range's value. If we call Method1(1, 20) without any value for range, then range is used with value of 100.

This comes in handy when most of the time a default value is used but sometimes we need to pass in the value to be used for a specific parameter. We can have default values for any number of parameters, the only condition being that they come at the end after all non-default parameters.

Named Parameters

When we use our Calc() method in our code, every time we need to look at the method declaration to see the order of min, max and range. If we mess up the order while calling, we might get some wrong/ unexpected results. By using named parameters, we can assign the values for parameters based on their names instead of just the order.

So, for example, we can do:

Calc(max:20, range:80, min:1)

So this way we explicitly mention the variable name followed by the value assigned to each. This is useful to avoid any confusion which may happen when you have long list of parameters. Although, if you have a long list of parameters then you might have other issues with the code, but at least named parameters are easier to understand and less prone to error.
Another thing to keep in mind is that named arguments must appear after all fixed arguments have been specified.

Variable Number of parameters

When we want to give the caller code flexibility with the number of parameters to pass, we can use "params" keyword like this:

void VariableParamsMethod(params int[] array)
{
      foreach (var num in array)
      {
           Console.WriteLine(num);
      }
}

So here, I can call this method as :

VariableParamsMethod(1, 2);
OR

VariableParamsMethod(1, 2, 3);

I can pass in any number of int arguments and the method will work. Isn't it amazing? Internally, the compiler converts these values into array.
Also, I can pass in an integer array. That will also behave as expected.

var array = new int[4] { 1, 2, 3, 4 };

VariableParamsMethod(array);


This feature comes in handy when we want to have the flexibility of different number of parameters
to be passed.
Params can be combined with other parameters with the condition that it should be the last one and can be specified only once.

Out and Ref Parameters

When we call a method, the regular parameters are copied in the method. For value types (which I discussed here), the values are copied whereas for reference types the reference is copied, pointing to the same object in the heap.
If we want the called method to use the same variable instead of creating a separate copy, we can use the "ref" or "out" keyword.
Let's look at an example:

void OutRefMethod(out int i, ref int j)
{
     i = 5;
     j = 6;
}

So if we call the method:

int i = 1, j = 1;
OutRefMethod(out i, ref j);

At the caller side, "i" will be set to 5 and "j" will be set to 6.
This comes in handy when we want a single method to return multiple things. With ref and out parameters we can set them inside our method and retrieve at the calling side. The difference between ref and out parameter is that ref requires variable to be initialized before it is passed to the method whereas out requires the variable to be set some value inside the method. We need to mention the out and ref keywords both at method definition and method calling time to make sure that it's intentional.

Another thing to note is that if you see a lot of out and ref parameters then there might be other issues in the code (likely disobeying Single Responsibility Principle as discussed here).


Conclusion

With different types of parameters, methods can become more powerful. We can use these features as and when we need them.

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


1 comment:

  1. thanks for sharing wonderful blog with us. its really more helpful to our institute candidates to get aware some useful knowledge keep sharing more information.
    Dot Net training in Chennai

    ReplyDelete