C# 언어 참조
bool(C# 참조)
bool 키워드는 System.Boolean의 별칭입니다. 이 키워드는 Boolean 값 true 및 false를 저장하는 변수를 선언하는 데 사용됩니다.
참고 |
|---|
| null 값도 가질 수 있는 부울 변수가 필요한 경우 bool을 사용하십시오. 자세한 내용은 nullable 형식(C# 프로그래밍 가이드)을 참조하십시오. |
리터럴
bool 변수에 부울 값을 할당할 수 있으며 bool 값으로 계산되는 식을 bool 변수에 할당할 수도 있습니다.
// keyword_bool.cs
using System;
public class MyClass
{
static void Main()
{
bool i = true;
char c = '0';
Console.WriteLine(i);
i = false;
Console.WriteLine(i);
bool Alphabetic = (c > 64 && c < 123);
Console.WriteLine(Alphabetic);
}
}
출력
True False False
변환
C++에서는 bool 형식의 값을 int 형식의 값으로 변환할 수 있습니다. 즉, false는 0과 같고 true는 0이 아닌 값과 같습니다. C#에서는 bool 형식과 다른 형식 간의 변환이 없습니다. 예를 들어, 다음 if 문은 C#에서는 유효하지만 C++에서는 유효하지 않습니다.
int x = 123;
if (x) // Invalid in C#
{
printf_s("The value of x is nonzero.");
}
int 형식의 변수를 테스트하려면 다음과 같이 이 변수를 명시적으로 특정 값(예: 0)과 비교해야 합니다.
int x = 123;
if (x != 0) // The C# way
{
Console.Write("The value of x is nonzero.");
}
예제
이 예제에서는 키보드로 문자를 입력한 후 입력한 문자가 영문자인지를 검사합니다. 영문자일 경우 대/소문자 여부를 검사하여 이러한 검사를 수행하는 데는 IsLetter 및 IsLower가 사용되며 이 둘은 모두 bool 형식을 반환합니다.
// keyword_bool_2.cs
using System;
public class BoolTest
{
static void Main()
{
Console.Write("Enter a character: ");
char c = (char)Console.Read();
if (Char.IsLetter(c))
{
if (Char.IsLower(c))
{
Console.WriteLine("The character is lowercase.");
}
else
{
Console.WriteLine("The character is uppercase.");
}
}
else
{
Console.WriteLine("Not an alphabetic character.");
}
}
}
입력
X
샘플 출력
Enter a character: X The character is uppercase. Additional sample runs might look as follow: Enter a character: x The character is lowercase. Enter a character: 2 The character is not an alphabetic character.
C# 언어 사양
bool 및 관련 주제에 대한 자세한 내용은 C# 언어 사양에서 다음 단원을 참조하십시오.
-
4.1.8 bool 형식
-
7.9.4 부울 같음 연산자
-
7.11.1 부울 조건부 논리 연산자
참고 항목
참조
C# 키워드정수 계열 형식 표(C# 참조)
기본 제공 형식 표(C# 참조)
암시적 숫자 변환 표(C# 참조)
명시적 숫자 변환 표(C# 참조)
참고