C# Programming - Functions and Subroutines - Discussion

Discussion :: Functions and Subroutines - General Questions (Q.No.1)

1. 

Which of the following will be the correct output for the C#.NET program given below?

namespace IndiabixConsoleApplication
{ 
    class SampleProgram
    {
        static void Main(string[] args)
        { 
            int num = 1;
            funcv(num); 
            Console.Write(num + ", "); 
            funcr(ref num); 
            Console.Write(num + ", ");
        }
        static void funcv(int num)
        { 
            num = num + 10; Console.Write(num + ", ");
        }
        static void funcr (ref int num)
        { 
            num = num + 10; Console.Write(num + ", ");
        } 
    } 
}

[A]. 1, 1, 1, 1,
[B]. 11, 1, 11, 11,
[C]. 11, 11, 11, 11,
[D]. 11, 11, 21, 11,
[E]. 11, 11, 21, 21,

Answer: Option B

Explanation:

No answer description available for this question.

Vishnu Vardahan said: (Aug 23, 2011)  
Please explain this program.

Bjl said: (Aug 10, 2012)  
When we call funcv(num); it will not affect on the value of 'num' because we are not assigning the changed value of it to the original variable. but,

When we change the value of variable(marked with 'ref' keyword) will change the value of original variable .

Here, the function
static void funcr (ref int num)
{
num = num + 10; Console.Write(num + ", ");
}

Will change the value of 'num' by 11 when it returns to the calling code.
so, the output will be 11 1 11 11

Vishnu said: (Nov 14, 2012)  
please see the difference of using the key word ref.

Any changes that take place in the method affect the original variable in the calling program.

class PassingRefByRef
{
static void Change(ref int[] pArray)
{
// Both of the following changes will affect the original variables:
pArray[0] = 888;
pArray = new int[5] {-3, -1, -2, -3, -4};
System.Console.WriteLine("Inside the method, the first element is: {0}", pArray[0]);
}

static void Main()
{
int[] arr = {1, 4, 5};
System.Console.WriteLine("Inside Main, before calling the method, the first element is: {0}", arr[0]);

Change(ref arr);
System.Console.WriteLine("Inside Main, after calling the method, the first element is: {0}", arr[0]);
}
}
/* Output:
Inside Main, before calling the method, the first element is: 1
Inside the method, the first element is: -3
Inside Main, after calling the method, the first element is: -3
*/

Rifathapps said: (May 3, 2016)  
Here, ref mean : the value change.

So, without ref the answer should be like this 11, 1, 11, 1.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.