bool(C# 참조)
Visual Studio 2008
업데이트: 2007년 11월
bool 키워드는 System.Boolean의 별칭입니다. 이 키워드는 Boolean 값 true 및 false를 저장하는 변수를 선언하는 데 사용됩니다.
참고: |
|---|
null 값도 가질 수 있는 부울 변수가 필요한 경우 bool?를 사용하십시오. 자세한 내용은 nullable 형식(C# 프로그래밍 가이드)을 참조하십시오. |
bool 변수에 부울 값을 할당할 수 있으며 bool 값으로 계산되는 식을 bool 변수에 할당할 수도 있습니다.
public class BoolTest { static void Main() { bool b = true; // WriteLine automatically converts the value of b to text. Console.WriteLine(b); int days = DateTime.Now.DayOfYear; // Assign the result of a boolean expression to b. b = (days % 2 == 0); if (true == b) { Console.WriteLine("days is an even number"); } else { Console.WriteLine("days is an odd number"); } } } /* Output: True days is an <even/odd> number */
C++에서는 bool 형식의 값을 int 형식의 값으로 변환할 수 있습니다. 즉, false는 0과 같고 true는 0이 아닌 값과 같습니다. C#에서는 bool 형식과 다른 형식 간의 변환이 없습니다. 예를 들어 다음 if 문은 C#에서 유효하지 않습니다.
int x = 123; // if (x) // Error: "Cannot implicitly convert type 'int' to 'bool'" { Console.Write("The value of x is nonzero."); }
int 형식의 변수를 테스트하려면 다음과 같이 이 변수를 명시적으로 특정 값(예: 0)과 비교해야 합니다.
if (x != 0) // The C# way { Console.Write("The value of x is nonzero."); }
이 예제에서는 키보드로 문자를 입력한 후 입력한 문자가 영문자인지를 검사합니다. 입력한 문자가 영문자이면 대/소문자를 검사합니다. 이러한 검사를 수행하는 데는 IsLetter 및 IsLower가 사용되며 이 둘은 모두 bool 형식을 반환합니다.
public class BoolKeyTest { 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."); } } } /* Sample Output: Enter a character: X The character is uppercase. Enter a character: x The character is lowercase. Enter a character: 2 The character is not an alphabetic character. */
참고: