0
0
C Sharp (C#)programming~5 mins

Comparison operators in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Comparison operators help you check if things are equal, bigger, or smaller. This lets your program make decisions.

Checking if a user entered the correct password
Deciding if a number is positive, negative, or zero
Comparing two scores to find the winner
Finding out if a value is within a certain range
Stopping a loop when a condition is met
Syntax
C Sharp (C#)
value1 == value2
value1 != value2
value1 > value2
value1 < value2
value1 >= value2
value1 <= value2

Use == to check if two values are equal.

Use != to check if two values are not equal.

Examples
This checks if a is less than b. It is true because 5 is less than 10.
C Sharp (C#)
int a = 5;
int b = 10;
bool result = a < b;  // true
This checks if the name is "Bob". It is false because the name is "Alice".
C Sharp (C#)
string name = "Alice";
bool isEqual = name == "Bob";  // false
This checks if x is not equal to 3.5. It is false because x is exactly 3.5.
C Sharp (C#)
double x = 3.5;
bool notEqual = x != 3.5;  // false
Sample Program

This program checks if a person is old enough to vote by comparing their age to the required age. It also checks if the age is exactly the required age.

C Sharp (C#)
using System;

class Program
{
    static void Main()
    {
        int age = 20;
        int requiredAge = 18;

        if (age >= requiredAge)
        {
            Console.WriteLine("You are old enough to vote.");
        }
        else
        {
            Console.WriteLine("You are not old enough to vote.");
        }

        bool isEqual = (age == requiredAge);
        Console.WriteLine($"Is age exactly {requiredAge}? {isEqual}");
    }
}
OutputSuccess
Important Notes

Remember to use double equals == for comparison, not a single equals =, which is for assignment.

Comparison operators return a bool value: true or false.

You can use comparison operators with numbers, characters, and strings.

Summary

Comparison operators let you compare two values.

They return true or false depending on the comparison.

Use them to make decisions in your program.