c#

c# ref return

fd27 2021. 4. 13. 17:59
class Product
{
    private int price = 100;

    public ref int GetPrice()
    {
        return ref price;
    }

    public void PrintPrice()
    {
        Console.WriteLine($"Price: {price}");
    }
}

internal class Program
{
    public static void Main(string[] args)
    {
        Product carrot = new Product();
        carrot.PrintPrice();
        ref int ref_local_price = ref carrot.GetPrice();
        int normal_local_price = carrot.GetPrice();
        ref_local_price = 10;
        Console.WriteLine(ref_local_price);
        Console.WriteLine(normal_local_price);
        carrot.PrintPrice();
    }
}

/*
Price: 100
10
100
Price: 10
*/

return: 값을 반환

ref return: 참조를 반환