Boolean type
Peponi │ 11/14/2024 │ 3m
C#
SyntaxTypebool
Boolean type
11/14/2024
3m
Peponi
C#
SyntaxTypebool
1. Introduction
bool (논리형) 형식은 참 (true), 거짓 (false) 을 나타낸다. .NET 형식은 System.Boolean이다. 주로 논리 연산 및 플래그 용도로 사용되며 기본값은 false이다. 다음은 bool이 사용될 수 있는 식 또는 문의 종류이다.
2. bool 초기화
리터럴 true 또는 false를 이용하여 초기화한다.
bool boolean = true;
bool boolean2 = false;3. Tri state boolean
값이 세 개인 논리형이 필요한 경우 (지뢰찾기 게임 같은 경우), bool? (Nullable bool) 형식을 사용할 수 있다. bool? 형식에는 true, false, null을 할당할 수 있다. 대체제로, 적당하게 정의된 열거형 형식을 이용할 수도 있다.
4. bool 값 변환
bool 값으로 변환하기 위해 많은 방법을 사용할 수 있다. 아래는 대표적인 예시들이다.
// string 값은 대소문자를 가리지 않는다
bool X = bool.Parse("TrUe"); // true// return 값이 true이면 out bool 값이 유효하다
bool isSuccess = bool.TryParse("TRUe",out bool result); // truebool X = Convert.ToBoolean("truE"); // true// 숫자 형식의 값을 넣는 경우, 0이 아니면 참이다
bool X = Convert.ToBoolean(-4.156); // true
bool X = Convert.ToBoolean(123); // true
bool X = Convert.ToBoolean(0); // false아래는 bool 값을 문자열, 정수 형식으로 변환하는 예시다.
bool X = true;
string convertString = X.ToString(); // True
int convertInt = Convert.ToInt32(X); // 1
X = false;
string convertString = X.ToString(); // False
int convertInt = Convert.ToInt32(X); // 0