ref and out parameters in C#
ref and out both are types of passing arguments by reference to a function, only the rules to use them are slightly different which actually are decisive for us on where they should be used.
When passing parameters with 'out' it is must for the function to assign (or modify) the values of parameters, otherwise the compiler givers compile time error. It is fine even if we don't assign values to them before passing, compiler guarantees that they will be initialized in the function.
When passing parameters with 'ref' type, it is fine even if the called function doesn't assign or modify their values but they must be initialized before passing to the function.
Consider following example:
public static void swap( ref int n1, ref int n2) { int temp = n1; n1 = n2; n2 = temp; }
This function takes 2 parameters by 'ref' type and the functions swaps their values inside the body.
int num1 = 40; int num2 = 50; swap( ref num1, ref num);
After this function call the values of num1 and num2 will be 50 and 40 resp. Now let's look at an example of 'out' parameters.
public static void calculate(float radius, out double area, out double circum) { area = 3.14 * radius * radius; circum = 2 * 3.14 * radius; }
Here the function calculate(), takes two arguments of type 'out' and assigns some values to them (area and circumference of a circle with no surprise). Here, if the function doesn't assign the value to out arguments compiler throws an error.
public static void calculate(float radius, out double area, out double circum) { //area = 3.14 * radius * radius; circum = 2 * 3.14 * radius; }
If we comment out the line assigning value to the variable area, then we will get an error as:
The out parameter 'area' must be assigned to before control leaves the current method.
Conclusion:
If we don't know how many arguments may be passed to our function or this number is not fixed then in such cases there is another type of parameter passing in C#, where parameters are received by the function with 'params' keyword. Go to this post to read about it.
0 comments: