C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: In the C# language, the if-statement requires that its expression be evaluated in a bool context.
And: This means you may sometimes need to explicitly specify the comparison—you cannot directly test integers.
C# program that uses true
using System;
class Program
{
static void Main()
{
// Reachable.
if (true)
{
Console.WriteLine(1);
}
// Expressions can evaluate to true or false.
if ((1 == 1) == true)
{
Console.WriteLine(2);
}
// While true loop.
while (true)
{
Console.WriteLine(3);
break;
}
// Use boolean to store true.
bool value = true;
// You can compare bool variables to true.
if (value == true)
{
Console.WriteLine(4);
}
if (value)
{
Console.WriteLine(5);
}
}
}
Output
1
2
3
4
5
First: In the first if-statement, we see that when an expression evaluates to false, the code inside the if-block is not reached.
Bool: You can set a bool variable to false. You can invert the value of a bool variable with the exclamation operator.
Finally: The expression != false is equal to == true. This can be entirely omitted.
Tip: It is usually clearer to express conditions in terms of truth rather than testing against false, but sometimes false may be clearer.
C# program that uses false literal
using System;
class Program
{
static void Main()
{
// Unreachable.
if (false)
{
Console.WriteLine(); // Not executed.
}
// Use boolean to store true and false.
bool value = true;
Console.WriteLine(value); // True
value = false;
Console.WriteLine(value); // False
value = !value;
Console.WriteLine(value); // True
// Expressions can be stored in variables.
bool result = (1 == int.Parse("1")) != false;
Console.WriteLine(result); // True
}
}
Output
True
False
True
True
Frequent: The true keyword is very frequently used. There are some subtleties to its use, particularly in assignments to expressions.
Tip: If-statements and while-statements require a bool processing context, which mandates the usage of true—or false.