본문 바로가기

.NET/C#

[C#] ref & out

ref

  • ref를 사용하여 매개 변수를 참조로 전달할 때 메소드가 원래 변수의 값을 직접 수정할 수 있도록 허용한다.
  • 메소드 내부의 매개 변수에 대한 변경 사항이 원래 변수에 영향을 미친다는 것을 의미한다.
  • 외부의 변수의 값은 변경하려는 경우
void ModifyValue(ref int value)
{
    value = 42;
}

int number = 10;
ModifyValue(ref number);
Console.WriteLine(number);  // Output: 42

out

  • ref 키워드와 유사하나, 파라미터로 넘기기 전에 변수 값의 초기화가 필요하지 않다.
  • 매서드 내부에서 생성된 값을 반환하려는 경우
void GetValues(out int x, out int y)
{
    x = 10;
    y = 20;
}

int a, b;
GetValues(out a, out b);
Console.WriteLine(a);  // Output: 10
Console.WriteLine(b);  // Output: 20
bool TryParse(string input, out int result)
{
    if (int.TryParse(input, out int parsedValue))
    {
        result = parsedValue;
        return true;
    }
    else
    {
        result = 0;
        return false;
    }
}

string userInput = "123";
if (TryParse(userInput, out int parsedNumber))
{
    Console.WriteLine($"Parsed number: {parsedNumber}");
}

 

Reference

 

C# ref Keyword

C# ref and C# out keywords are used in method parameters. This article helps you decide whether to use a ref or out keyword, especially when the parameter types are value types.

www.c-sharpcorner.com

 

C# ref, out 두 한정자의 차이점, 매개변수 사용법 차이

C# ref, out - 두 한정자의 차이점 참조로 전달 Java와 C# 모두에서 개체를 참조하는 메서드 『매개 변수는 항상 참조로 전달』되는 반면 기본 데이터 형식 매개 변수(C#의 값 형식)는 값으로 전달됩니

codingcoding.tistory.com

 


There might be incorrect information or outdated content.

 

 

'.NET > C#' 카테고리의 다른 글

[C#] Parse 사용시 발생하는 이슈 🔥  (0) 2023.11.23
[C#] First, FirstOrDefault  (1) 2023.09.21
[C#] (delegate) Action & Func & Predicate  (0) 2023.08.18
[C#] delegate  (0) 2023.08.17
[C#] C# 은 this 를 사용하지 않는가?  (0) 2023.07.29