C# Programming - Functions and Subroutines - Discussion

Discussion Forum : 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 + ", ");
        } 
    } 
}
1, 1, 1, 1,
11, 1, 11, 11,
11, 11, 11, 11,
11, 11, 21, 11,
11, 11, 21, 21,
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
4 comments Page 1 of 1.

RifathApps said:   9 years ago
Here, ref mean : the value change.

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

Vishnu said:   1 decade ago
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
*/

Bjl said:   1 decade ago
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 vardahan said:   1 decade ago
Please explain this program.

Post your comments here:

Your comments will be displayed after verification.