ref in C# -- ref -- C#

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值