본문 바로가기

C# Convert, Parse와 TryParse

@코야딩구2025. 6. 10. 15:00

Lv1. 데이터와 연산자 - 1. 데이터 다루기 중 6번 문제

▶ Convert 와 Parse의 차이 (+TryParse)

1. Convert는 기본 데이터 형식을 다른 기본 데이터 형식으로 변환한다. 형변환 실패시 오류가 뜬다.

// Convert == 기본 데이터 형식을 다른 기본 데이터 형식으로 변환한다. 형변환 실패시 오류가 뜬다.(실행 불가)
string strA = "10";
string strB = "12.345";
string strC = null; // null == 0
string strD = "";

int n1 = Convert.ToInt32(strA);  // 10
//int n2 = Convert.ToInt32(strB);  // FormatException, 오류, 컴파일 불가
int n3 = Convert.ToInt32(strC); //  null == 0이라 0으로 바뀜
// int n4 = Convert.ToInt32(strD); // FormatException, 빈공간은 null과 다름
Console.WriteLine("Convert: " + strA + "->" + n1 + '\n' + "Convert: " + strC + "->" + n3);
// 출력:
// Convert: 10->10
// Convert: ->0    **null은 빈공간으로 출력됨

 

2. Parse는 문자열 표현을 해당하는 형 으로 변환한다. 마찬가지로 형변환 실패시 오류가 뜬다.

// Parse == 문자열 표현을 해당하는 형 으로 변환한다. 마찬가지로 형변환 실패시 오류가 뜬다.(실행 불가)
string strA = "10";
string strB = "12.345";
string strC = null;
string strD = "";

int n1 =Int32.Parse(strA);  // 10
//int n2 =Int32.Parse(strB);  // FormatException, 오류
//int n3 =Int32.Parse(strC);  // ArgumentNullException, null은 문자열 표현이 아니라 오류,
//int n4 =Int32.Parse(strD);  // ArgumentNullException, 빈공간도 문자열 표현이 아닌듯하다.
Console.WriteLine("Parse: " + strA + "->" + n1);
// 출력:
// Parse: 10->10

 

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

// TryParse == 문자열 표현을 해당하는 형 으로 변환한다. 반환 값은 변환의 성공 여부를 나타낸다.
// 형변환 실패시 기본 값으로 초기화된다.
string strA = "10";
string strB = "12.345";
string strC = null;
string strD = "";

int n1, n2, n3, n4;
bool b1 = Int32.TryParse(strA, out n1);
bool b2 = Int32.TryParse(strB, out n2);
bool b3 = Int32.TryParse(strC, out n3);
bool b4 = Int32.TryParse(strD, out n4);
Console.WriteLine("TryParse: " + b1 + ", " + strA + "->" + n1);
Console.WriteLine("TryParse: " + b2 + ", " + strB + "->" + n2);
Console.WriteLine("TryParse: " + b3 + ", " + strC + "->" + n3);
Console.WriteLine("TryParse: " + b4 + ", " + strD + "->" + n4);
// TryParse: True, 10->10        == 변환 성공
// TryParse: False, 12.345->0    == 변환 실패, 실패한 값은 0으로 초기화
// TryParse: False, ->0
// TryParse: False, ->0
float f1, f2, f3, f4;
b1 = float.TryParse(strA, out f1);
b2 = float.TryParse(strB, out f2);
b3 = float.TryParse(strC, out f3);
b4 = float.TryParse(strD, out f4);
Console.WriteLine("TryParse: " + b1 + ", " + strA + "->" + f1);
Console.WriteLine("TryParse: " + b2 + ", " + strB + "->" + f2);
Console.WriteLine("TryParse: " + b3 + ", " + strC + "->" + f3);
Console.WriteLine("TryParse: " + b4 + ", " + strD + "->" + f4);
// TryParse: True, 10->10          * 10은 int형으로 볼 수 있으나, 실수형에도 똑같이 사용가능
// TryParse: True, 12.345->12.345
// TryParse: False, ->0
// TryParse: False, ->0

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

C# 박싱과 언박싱  (0) 2025.07.07
C# 문자열  (0) 2025.06.17
C# is와 as (Type Checking and Casting)  (0) 2025.06.11
C# ref vs out (Pass by Reference)  (0) 2025.06.11
C# 문법 기초 - C++과 다른 점  (5) 2025.06.09
목차