Introduction
In C#, the keyword ref is used for passing by reference.
ref
In parameter
Example
Class
void Method(ref int refArgument)
{
refArgument = refArgument + 44;
}
Main
static void Main()
{
int number = 1;
Method(ref number);
Console.WriteLine(number);
}
Output
45
In return statement
A reference return value is defined by using the ref
keyword.
To return a reference value, it is neccessary to use keywords both in
return statement
Before keyword return in function or method definition
The assignment to the variable with modifier ref.
For more detailed explanation, see the following examples.
Example
public class Book
{
public string Author;
public string Title;
}
public class BookCollection
{
private Book[] books = { new Book { Title = "Call of the Wild, The", Author = "Jack London" },
new Book { Title = "Tale of Two Cities, A", Author = "Charles Dickens" }
};
private Book nobook = null;
public ref Book GetBookByTitle(string title)
{
for (int ctr = 0; ctr < books.Length; ctr++)
{
if (title == books[ctr].Title)
return ref books[ctr];
}
return ref nobook;
}
public void ListBooks()
{
foreach (var book in books)
{
Console.WriteLine($"{book.Title}, by {book.Author}");
}
Console.WriteLine();
}
}
Main
static void Main()
{
var bc = new BookCollection();
bc.ListBooks();
ref var book = ref bc.GetBookByTitle("Call of the Wild, The");
if (book != null)
{
book = new Book { Title = "Republic, The", Author = "Plato" };
}
bc.ListBooks();
}
Output
The example displays the following output look like this:
Call of the Wild, The, by Jack London
Tale of Two Cities, A, by Charles Dickens
Republic, The, by Plato
Tale of Two Cities, A, by Charles Dickens
Notice
Other post
ref v.s. in v.s. out
(7条消息) Pass by reference in C#, out, in, ref -- C#_xxcghjhkhjgjk的博客-CSDN博客
Ref
ref keyword - C# Reference | Microsoft Learn