본문 바로가기

C#

[C#] Parse, TryParse, Convert

 

Parse

 

문자열 표현을 해당하는 형으로 변환한다.

ToString()과 비슷한 표현.

 

       	   string str = String.Empty;

            try
            {
                int result = int.Parse(str);
                Console.WriteLine(result);

            }
            catch (FormatException e)
            {
                Console.WriteLine(e.Message);
            }
            // '' 파싱 불가
            // 예외 발생

 

 

Convert

 

기본 데이터 형식을 다른 기본 데이터 형식으로 변환한다.

Boolean, Char, Byte, Double, String, DateTime 등의 형식들을 지원한다.

string 타입을 int 타입으로 바꿀 수 있는 값들은 변환이 잘 되지만,

정수가 아닌 실수형이거나, 숫자가 아닌 문자열이 할당되어 있다면 FormatException이 발생한다.

null 값이 들어있는 경우 0이 반환된다.

 

    	    int num = -1;
            bool flag = true;

            while (flag)
            {
                Console.Write("숫자를 입력하세요 : ");
                string input = Console.ReadLine();

                try
                {
                    num = Convert.ToInt32(input);

                    if(num <= Int32.MaxValue)
                    {
                        Console.WriteLine("결과 값 : " + num);
                    }
                    else
                    {
                        Console.WriteLine("입력 값이 범위를 벗어났습니다.");
                    }
                }
                catch (FormatException e)
                {
                    Console.WriteLine(e.Message);
                }
                catch (OverflowException e2)
                {
                    Console.WriteLine(e2.Message);
                }

                Console.Write("다시 실행하시겠습니까? (Y/N) : ");
                string answer = Console.ReadLine();

                if(answer.ToUpper() != "Y")
                {
                    Console.WriteLine("프로그램을 종료합니다.");
                    flag = false;
                }

            }

 

 

TryParse

 

문자열 표현을 해당하는 형으로 변환한다. 반환값은 변환의 성공 여부를 나타낸다.

Convert와 Parse는 단순한 값만 변환하고 반환했는데,

TryParse는 변환의 성공 여부, 즉, true/false 값을 반환한다.

 

   	    string strA = "10";
            string strB = "12.345";
            string strC = null;

            int i;
            Console.WriteLine(Int32.TryParse(strA, out i)); // true
            Console.WriteLine(Int32.TryParse(strB, out i)); // false
            Console.WriteLine(Int32.TryParse(strC, out i)); // false

 

'C#' 카테고리의 다른 글

[C#] ?. ?? 연산자  (0) 2022.12.11
[C#] delegate  (0) 2022.10.10
[C#] 제네릭 generic  (0) 2022.10.10
[C#] 확장 메소드 Extension Method  (0) 2022.10.07
[C#] 접근 제한자 Access Modifier  (0) 2022.10.07