C# 기본) 형 변환

guk (Guk)·2021년 10월 29일
0

C Sharp-basic

목록 보기
1/5
post-thumbnail
  • 가장 간단한 형 변환 : 정수 -> 실수 형변환
int a = 500;
float b = (float)a;

1. Convert

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

표시 형식메서드
DecimalConvert.ToDecimal(a)
floatConvert.ToSingle(a)
doubleConvert.ToDouble(a)
shortConvert.ToInt16(a)
intConvert.ToInt32(a)
longConvert.ToInt64(a)
ushortConvert.ToUInt16(a)
uintConvert.ToUInt32(a)
ulongConvert.ToUInt64(a)
유니코드Convert.ToChar(a)
문자열Convert.ToString(a)

P . S

Console.WriteLine(Convert.ToInt32("12.345"))//문자열이 들어가면 FormatException발생
Console.WriteLine(Convert.ToInt32(null))//null이 들어가면 0을 출력

2. Parse

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

표시 형식메서드
DecimalDecimal.Parse(a)
floatSingle.Parse(a)
doubleDouble.Parse(a)
shortInt16.Parse(a)
intInt32.Parse(a)
longInt64.Parse(a)
ushortUInt16.Parse(a)
uintUInt32.Parse(a)
ulongUInt64.Parse(a)
charConvert.ToChar(a)

P . S

Int32.Parse(null)// ArgumetNullException 오류발생. null은 안됨

3. TryParse : 반환 성공 여부

위 2개는 단순히 값만 변환하지만 TryParse는 반환이 가능한지를 알려준다.

  • 기본 형태
Int32.TryParse(a, out i)//a변수를 int형으로 변환이 가능한지 확인함. i에는 변환가능하면 10, 불가능하면 0을 반환.
  • 예시
Console.WriteLine(Int32.TryParse("10", out i) + ", i=" + i); //
Console.WriteLine(Int32.TryParse("12.345", out i) + ", i=" + i);
Console.WriteLine(Int32.TryParse(null, out i) + ", i=" + i);

profile
개발자 블로그 및 이것저것

0개의 댓글