Книга: C# 2008 Programmer

Relational Operators

Relational Operators

You use relational operators to compare two values and the result of the comparison is a Boolean value — true or false. The following table lists all of the relational operators available in C#.

Operator Description
== Equal
!= Not equal
> Greater than
>= Greater than or equal to
< Lesser than
<= Lesser than or equal to

The following statements compare the value of num with the numeric 5 using the various relational operators:

int num = 5;
Console.WriteLine(num == 5); //---True---
Console.WriteLine(num != 5); //---False---
Console.WriteLine(num > 5); //---False---
Console.WriteLine(num >= 5); //---True---
Console.WriteLine(num < 5); //---False---
Console.WriteLine(num <= 5); //---True---

A common mistake with the equal relational operator is omitting the second = sign. For example, the following statement prints out the numeric 5 instead of True:

Console.WriteLine(num = 5);

A single = is the assignment operator.

C programmers often make the following mistake of using a single = for testing equality of two numbers:

if (num = 5) //---use == for testing equality---
{
Console.WriteLine("num is 5");
}

Fortunately, the C# compiler will check for this mistake and issue a "Cannot implicitly convert type 'int' to 'bool'" error.

Оглавление книги


Генерация: 0.032. Запросов К БД/Cache: 0 / 0
поделиться
Вверх Вниз