Codiqo

Learn C# · lesson 10 of 61 · about 7 minutes

Comparisons and bool

Let the battle say when the Slime is beaten: compare values, store the answer in a bool, and compare strings.

What you'll learn

  • Use the six comparison operators
  • Store results in bool variables
  • Compare strings

Is the Slime beaten?

Your battle knows the Slime's HP, but not whether the Slime is beaten. A comparison answers a question like is its HP 0 or less? The answer is a bool, true or false, and C# prints it as True or False.

Asking questions

== != < > <= >= give a bool: True or False. In C#, == on strings compares the text, so name == "Ada" works as you'd expect. Use string.Compare(a, b) or a.CompareTo(b) to put text in alphabetical order.

A beaten Slime

int slimeHp = 0;
bool slimeDown = slimeHp <= 0;
Console.WriteLine($"Slime defeated: {slimeDown}");
Console.WriteLine(slimeHp < 0);
Console.WriteLine(slimeHp == 0);

Output

Slime defeated: True
False
True

Comparisons

int score = 72;
bool passed = score >= 50;
Console.WriteLine($"{passed} {score == 100}");
string answer = "def";
Console.WriteLine($"{answer == "def"} {answer.Equals("DEF", StringComparison.OrdinalIgnoreCase)}");

Output

True False
True True

Tip

In your code you write true and false in small letters, but C# prints them with a capital: True and False.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.