Lesson 3.3

C# Logical Operator – With Programming Examples


What is Logical operator in C#?
What is the symbol of Logical Operator?
How to use Logical Operator in program?

C# Logical Operator – With Programming Examples

The && and || are the called logical operator. Logical operator compares two conditions and return results in Boolean based on operator used. For example the AND (&&) operator return true if both conditions are true whereas the OR (||) operator returns true if any one of the condition is true. Let’s understand it with an easy example.

Logical Operator Symbol

&& (AND)It returns true if both conditions returns true. if(a==b && b == c)
|| (OR)It returns true if any one or both conditions returns true. if(a == b || b == c)
! (NOT)It returns true if condition returns false. if(!(x==5))

For example, you are creating a login application in which you are getting user name and password as input, comparing them with stored value and if condition matches you return a successful message to user.

Programming Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace logical_operator
    class Program
        static void Main(string[] args)
            string username, password;
            Console.WriteLine("Welcome to CompileCode.Net");
            Console.Write("Enter your User Name:\t");
            username = Convert.ToString(Console.ReadLine());
            Console.Write("Enter your password:\t");
            password = Convert.ToString(Console.ReadLine());

            if (username == "user1" && password == "pass123")
                Console.WriteLine("You have logged in Successfully");
            else if (username == "user1" || password == "pass123")
                Console.WriteLine("Either username or password is incorrect");
                Console.WriteLine("Couldn't Login");



Welcome to CompileCode.Net
Enter your User Name:     user1
Enter your password:     pass123
You have logged in Successfully


In this chapter you have learned what is Logical operator, their symbol is and how to use it in your c# program. In the next chapter we will learn about Bitwise Operators in C#.