This set of C# Question Bank on “Use of Ref and Out Parameters”.
1. What will be the output of the following C# code?
-
class Program
-
{
-
static void Main(string[] args)
-
{
-
int i = 5;
-
int j;
-
method1(ref i);
-
method2(out j);
-
Console.writeline(i + " " + j);
-
}
-
static void method1(ref int x)
-
{
-
x = x + x;
-
}
-
static void method2(out int x)
-
{
-
x = 6;
-
x = x * x;
-
}
-
}
a) 36, 10
b) 10, 36
c) 0, 0
d) 36, 0
Answer: b
Clarification: Variable ‘i’ is passed as reference parameter declared with ‘ref’ modifier and variable ‘j’ is passed as a output parameter declared with ‘out’ keyword. Reference parameter used to pass value by reference is the same with out parameter.
Output :
2. Statements about ‘ref’ keyword used in C#.NET are?
a) The ref keyword causes arguments to be passed by reference
b) While using ‘ref’ keyword any changes made to the parameter in the method will be reflected in the variable when control is passed back to the calling method
c) Ref usage eliminates overhead of copying large data items
d) All of the mentioned
Answer: d
Clarification: None.
3. What will be the output of the following C# code?
-
static void main(string[] args)
-
{
-
int n = 1;
-
method(n);
-
console.Writeline(n);
-
method1(ref n);
-
console.Writeline(n);
-
}
-
static void method(int num)
-
{
-
num += 20;
-
console.writeline(num);
-
}
-
static void method1(ref int num)
-
{
-
num += 20;
-
console.writeline(num);
-
}
a)
1 1 1 1
b)
21 1 21 21
c)
11 21 21 11
d)
21 1 21 21
View Answer
Clarification: None.
Output :
4. Which method does following C# code explains?
-
static void Main(string[] args)
-
{
-
int a = 10, b = 20;
-
method(ref a, ref b);
-
console.writeline(a + " " + b);
-
}
-
static void swap(ref int i, ref int j)
-
{
-
int t;
-
t = i;
-
i = j;
-
j = t;
-
}
a) Call by reference
b) Call by value
c) Output parameter
d) parameter arrays
Answer: a
Clarification: The following set of code explains swapping of numbers by reference parameters which makes usage of call by reference process.
5. What will be the output of the following C# code?
-
static void main(string[] args)
-
{
-
int []arr = new int[]{ 1, 2, 3, 4, 5};
-
fun (ref arr);
-
for (int i = 0; i < arr.Length ; i++)
-
Console.WriteLine( arr[i] + " ");
-
}
-
static void fun(ref int[]a)
-
{
-
a = new int[6];
-
a[3] = 32;
-
a[1] = 24;
-
}
a) 0, 0, 32, 0, 0, 0
b) 0, 24, 0, 32, 0, 0
c) 24, 0, 32, 0, 0, 0
d) 0, 0, 32, 0, 0, 0
Answer: b
Clarification: index positions which are assigned the new values are passed as a reference parameter and hence rest positions are filled with zero values.
Output :