I'm doing a challenge from a book and it's asking me to create a loop that counts down from 20 to 0 and has me print a message for each number. However, it's asking me to print out a special message for each number divisible by 5. I have seen certain examples including this one:
if (number%5==0)
{
//your code here
}
I get what the modulo is doing, but why does this code have ==0
after it? For example, why not just code it like this:
if (number%5)
{
//your code here
}
Because number%5
is an integer between 0 and 4, while number%5==0
is a boolean. Unlike languages like C/C++ where integers can be considered booleans (0 -> false, 1 -> true for example), in C# the condition of an if must be a 'real' boolean.
(Even if C# let you use an integer in an if condition, your suggested change to the code is incorrect. The former piece of code would run your code if number%5 is 0, the latter piece of code would run your code if number%5 is NOT 0.)
EDIT: As Eric Lippert says in the comments, an alternative to using a bool
in an if
condition is to use something that implements implicit operator bool
as a cast or implements operators true
and false
, such as http://msdn.microsoft.com/en-us/library/6x6y6z4d.aspx . But as far as I can tell, no primitives besides bool
satisfy either of these.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With