In this article
Overview
bool
type is a data type that represents logical values that accept either true
or false
.
- Although a Boolean value requires only one bit of storage, the runtime will use one byte of memory. because this is the minimum chunk that the runtime and processor can efficiently work with.
- To avoid space inefficiency in the case of arrays, .NET provides
BitArray
class in the System.Collections namespace that’s designed to use just one bit per Boolean value.
Boolean Conversions
No cast conversions can be made from the bool type to numeric types, or vice versa.
Equality and Comparison Operators
Operator | Usage |
---|---|
== | equality |
!= | inequality |
> | greater than |
>= | greater than or equal |
< | Less than |
<= | Less than or equal |
Syntax
operandA
operand B
Notes
- Equality and comparison operations always return a boolean value (
true
orfalse
). - Value types typically have a very simple notion of equality:
int x = 1;
int y = 2;
int z = 1;
Console.Writeline(x==y); // False
Console.Writeline(x==z); // True
- Reference types, equality, by default, is based on reference, as opposed to the actual value of the underlying object.
Dude d1 = new Dude("John");
Dude d2 = new Dude("John");
Console.WriteLine(d1==d2); // False
Dude d3 = d1;
Console.WriteLine(d3==d1); // True
- Equality and comparison operators, work for all numeric types, but you should use them with caution with real numbers.
- The comparison operators also work on enum type members by comparing their underlying integral-type values.
Conditional Operators
- The
&&
and||
operators test forand
andor
conditions. - They are frequently used in conjunction with the
!
operator, which expresses not. - The
&&
and||
operators short-circuit evaluation when possible.
- while using
&&
operator if the first operand evaluates to false, then the whole expression evaluates to false.- but for
||
operator, if the first operand evaluates totrue
, the whole expression evaluates totrue
.
- Short-circuiting is essential in allowing expressions such as the following to run without throwing a
NullReferenceException
->if (sb != null && sb.Length > 0
, note that without short-circuiting thesb.Length
will throw that exception becausesb
is null here. - The
&
and|
operators also test for and and or conditions, the difference is that they do not short-circuit. also, they are rarely used in place of conditional operators.
Ternary Operator
The ternary operator (more commonly called the ternary operator because it’s the only operator that takes 3 operands).
Syntax
static int Max(int a, int b){
return (a>b) ? a : b;
}
The conditional operator is particularly useful in LINQ expresions.