ref is a parameter modifiers in C# that allow you to pass arguments to methods by reference, rather than by value. This means that changes made to the parameter inside the method will affect the original variable outside the method.
The ref keyword is used to pass a parameter by reference. When you pass a variable to a method using ref, both the caller and the callee have access to the same memory location.
Example:
using System;
class Calculator
{
public void multiplyByFive(ref int num)
{
num = num * 5; // Modify the original value
Console.WriteLine("num value in Inside method = " + num);
}
}
class MyExample
{
static void Main()
{
int number = 5;
Calculator cal = new Calculator();
// Pass number by reference using 'ref'
cal.multiplyByFive(ref number);
Console.WriteLine("num value in Outside method = " + number);
}
}
Output:
num value in Outside method = 25
Explanation:
- The num parameter in the multiplyByFive method is passed by reference using the ref keyword.
- The method multiplyByFive the value of num, and this change is reflected in the number variable outside the method.
C# ref Keyword – Interview Questions
Q 1: What is ref keyword?
Ans: It passes arguments by reference.
Q 2: Must ref variable be initialized?
Ans: Yes.
Q 3: Can ref change original value?
Ans: Yes.
Q 4: Is ref two-way communication?
Ans: Yes.
Q 5: Can ref be used with methods only?
Ans: Yes.
C# ref Keyword – Objective Questions (MCQs)
Q1. What is the purpose of the ref keyword in C#?
Q2. Which of the following must be true when using ref?
Q3. How do you pass an argument by reference using ref?
void Change(ref int x) { x = 10; }
Q4. Can ref be used with value types and reference types?
Q5. Which of the following is true when using ref?