Click here to Skip to main content
15,888,106 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
C#
using System;
static class boolclass
{
	public static void Main() 
	{
	int a = 1;
int b = 2;
// Which one is greater?
bool greaterAB = (a > b);
// Is 'a' equal to 1?
bool equalA1 = (a == 1);
// Print the results on the console
if (greaterAB )
{
Console.WriteLine("A > B");
}
else
{
Console.WriteLine("A <= B");
}
Console.WriteLine("greaterAB = " + greaterAB);
Console.WriteLine("equalA1 = " + equalA1);
// Console output:
// A <= B
// greaterAB = False
// equalA1 = True
Console.ReadKey(true);
	}
}



This point---

C#
if (greaterAB )


Does it assume that

C#
if (greaterAB)


is

C#
if (greaterAB == True)


More or less boolean default value is false so even if it assumes this, it should assume--

if (greaterAB == False)


What I have tried:

Googled it but I did not find anything which I could understand or is related to this.
Posted
Updated 24-Mar-16 8:59am
v2
Comments
CHill60 24-Mar-16 14:56pm    
The bit between the brackets is an expression that evaluates to either true or false. Default value has nothing to do with it. Nor is it making any assumptions. If the expression is true the statement following will be executed
Member 12414152 24-Mar-16 15:00pm    
Why??
We haven't specified hat it should only be executed when the expression is true.
Sascha Lefèvre 24-Mar-16 15:03pm    
That's the definition of the if-statement.
Member 12414152 24-Mar-16 15:17pm    
Ohhhh, thanks, I completely lost my mind.
Sascha Lefèvre 24-Mar-16 15:22pm    
You're welcome! ;-)

1 solution

C#
if (greaterAB)

and
C#
if (greaterAB == true)

are equivalent and the first version should be preferred.

In C# you can't use an un-initialized identifier and in fact you initialize greaterAB:
C#
bool greaterAB = (a > b);

So at this point it reflects the fact whether a is greater than b and a boolean's default value of false has nothing to do with all this. Now if you had declared greaterAB as a class variable (which wouldn't make much sense) then it would be initialized to the default value of false the first time the static class is being used or, if it's a non-static class, an object of that class is instantiated.
 
Share this answer
 
Comments
BillWoodruff 24-Mar-16 17:01pm    
+5
Sascha Lefèvre 24-Mar-16 17:15pm    
Thanks, Bill!
Sergey Alexandrovich Kryukov 24-Mar-16 19:38pm    
5ed.
—SA
Sascha Lefèvre 24-Mar-16 20:23pm    
Thanks, Sergey!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900