Answer: ref is a C# reference which is used to pass the reference types. It cannot pass the value types. This is mostly used in swapping implementations.
We have to declare it while writing a method and again need to use at calling point.
Example,
class MyClass
{
static void Reverse(ref string first, ref string second)
{
string name = first;
first = second;
second = name;
}
static void Main()
{
string firstName = "Krishna";
string lastName = "Vamshi";
Reverse(ref firstName, ref lastName); // Calling method
Console.WriteLine(firstName); // Vamshi
Console.WriteLine(lastName); // Krishna
}
}
In the above code, we have implemented a
swap method and interchanging the
first and
last names using
ref modifier.
Asked In: Spotted While Learning |
Alert Moderator