Logical Operators
Logical operators combine true-or-false questions, like 'do I have my ticket AND is the gate open?'. C# uses and, or, and not to make decisions from many conditions.
In this page:
Syntax
bool result = condition1 && condition2; // AND
bool result = condition1 || condition2; // OR
bool result = !condition; // NOT
Logical Operators
Logical operators combine boolean expressions: && (AND), || (OR), and ! (NOT). && and || short-circuit — if the left side already determines the result, the right side is never evaluated. This matters when the right side has side effects.
Note:
Short-circuiting lets you safely write
if (obj != null && obj.IsValid) without a null-check exception.Example: Logical Operators
using System;
class Program
{
static void Main(string[] args)
{
bool isLoggedIn = true;
bool isAdmin = false;
Console.WriteLine(isLoggedIn && isAdmin);
Console.WriteLine(isLoggedIn || isAdmin);
Console.WriteLine(!isAdmin);
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
&and|instead of&&and||, which do not short-circuit and always evaluate both sides. - Writing
x == 1 || 2, which does not compile because2is not a bool. - Relying on a method call in the right side of
&&always running when short-circuiting may skip it.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: