본문 바로가기
개발 기록/C#

[C# 기본기] out 키워드란?

by Ratataca 2021. 10. 25.

 

out 키워드란?

out 키워드와 같이 사용되는 매서드는 TryParse() 매서드이다. 

int.TryParse(), float.TryParse() 등 기본적인 숫자 자료형과 함께 사용된다. 

실제 함수는 이렇게 생겼다.

public static bool TryParse(string s, out int result);

 

기존에 우리가 형변환을 위해서 사용했던 Parse()에서 try-catch문이 포함되었다고 생각하면 쉽게 이해할 수 있다.

public static int Parse (string s, System.Globalization.NumberStyles style, IFormatProvider? provider);

 


기존 입력 방법

사용자 입력을 부터 형변환을 할때 예외처리를 한 코든 다음과 같다.

        static void Main(string[] args) {
            try {

                int input = int.Parse(Console.ReadLine());
                Console.WriteLine("입력 숫자 : {0} 입니다.", input);

            }
            catch {

                Console.WriteLine("int 형식으로 다시 입력해주세요");

            }
        }

try - catch 문을 사용하여 사용자로 부터 입력받은 값을 int로 변환하려고할 때 변환하기 어려운 상황이 되면  error가 발생하고 catch문 으로 넘어간다. 

 

out를 이용한 입력 방법

위 과정을 TryParse()를 이용해 간소화 할 수 있다.

int.TryParse("1234", out output);

 

따라서 우리는 프로그램을 할 때 TryParse(), out를 이용하면 입력에 대한 에외처리를 따로 하지 않아도 된다.

        static void Main(string[] args) {

            int input;

            bool result = int.TryParse(Console.ReadLine(), out input);


            if (result) {
                Console.WriteLine("입력 숫자 : {0} 입니다.", input);
            }
            else {
                Console.WriteLine("int 형식으로 다시 입력해주세요");
            }
        }

 

 

결과

 

 

댓글