낑깡의 게임 프로그래밍 도전기

C# Call by value, Call by reference 본문

C#

C# Call by value, Call by reference

낑깡겜플밍 2025. 7. 7. 10:35
반응형
static void Main(string[] args)
{
    int money = 1000;
    SetMoney(money);
}

static Void SetMoney(int money)
{
    money = 30000;
}

Call by value. 값 복사

SetMoney(ref money);에 static Void SetMoney(ref int money)를 하면 레퍼런스로 바뀌긴하나 쓰임을 구분하기 위해 웬만하면 쓰지 않는 것이 좋다. 차라리 return을 쓰는게 낫다.

static void Main(string[] args)
{
    GiftBox giftBox = new GiftBox(); //클래스
    {
        Money = 1000,
    };
    SetGiftBox(giftBox);
}

Static void SetGiftBox(GiftBox info)
{
    info.Money = 5000;
}

Call by reference

void SetMoney(out int needMoney)
*out은 무조건 초기화하지않으면 오류가 남(out를 더 선호하는 사람도 있다.)

void (int, int) SetMoney(int needMoney); //여러값 내보낼 때 쓰는 형식
*하지만 여러값을 내보낼땐 클래스나 구조체를 쓰는 것이 좋다

반응형