Practice mode C#

What is the output of: static void Inc(ref int a) => a++; int v = 1; Inc(ref v); Console.WriteLine(v);?

Correct answer D. 2

Explanation

The ref modifier passes the variable itself by reference, so the method's parameter a is an alias for v. Incrementing a changes v to 2. Without ref, the int would be copied and v would stay 1. The ref keyword must appear both in the method declaration and at the call site, and the argument must be definitely assigned beforehand.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.