Comparison operations C#
Blog > C# > Comparison operations C#

Comparison operations C#

PL

Comparison operations C#



Comparison operations C# – Comparing values during programming allows you to check the dependencies between variables. The result of the check is always true or false.


operacje logiczne
Comparison operations

Contents



C# provides the comparison operators listed below:


OperatorImportance
>Checks whether the first value is greater than the second.
<Checks whether the first value is smaller than the second.
>=Checks whether the first value is greater than or equal to the second.
<=Checks whether the first value is less than or equal to the second.
==Checks whether the first value is equal to the second.
!=Checks whether the first value is different from the second.

Examples of use


// compare two values and assign the result to a bool variable
bool sprawdz = 18 >= 7;


// use the result of a comparison in a conditional statement. The value obtained
// is true, so the code will be executed
if(sprawdz)
Console.WriteLine("Tak, 18 jest większe od 7");

// Display false, because 45 and 12 are not equal
Console.WriteLine(45 != 12 );

Console.WriteLine(45 == 40 + 5 ); // Displays true because operators
// comparisons are made after arithmetic operations - it will first perform
// adding, and later comparing.

// Display false, because 15 is not smaller than itself
Console.WriteLine(15 < 15 );

Possible error


Due to the diversity of languages, people starting programming in C/C++/C# sometimes have a problem checking if two values are equal. For such a check it is necessary to use the operator “==”. Using the “=” operator in this case will result in incorrect program operation or an error. In C/C++ for different types, and for C# only for bool, instead of comparing the value, it would be typed into the variable. The example below will explain the problem in more detail.


// Below an incorrect example

bool sprawdz = true;// bool variable with true value
if(sprawdz = false)// no comparison is made, the variable value is set
// on false and the following value is checked by the if condition statement
{
// this code will not be executed
}


// Below the second, also an incorrect example

bool sprawdz = true;// bool variable with true value
if(sprawdz = true)// no comparison is made, the variable value is set
// on true and this value is validated by the if condition statement
{
// this code will be executed
}


// Below is the correct example

bool sprawdz = false; //bool variable with false value
if(sprawdz == false) // The value of the "check" variable is compared to "false".
// The values are equal, so the conditional if statement gets the value "true"
// and goes to execute the code
{
// this code will be executed
}

×
Any questions?
TOP