This might sound silly. But I'm working on a C# assignment for school right now, and I can't get a simple if-else statement to work. Isn't the syntax the same as in C++ or Java?

I want to do one thing if a boolean variable is true, something else if it's not. The "bool" type exists in C#, right? ;)

Re: If-Else in C# 80 80
if("a"=="d") 
{
 //do something
} 
else if("a"=="c") 
{
 // do something else
}
else 
{
 //do something if i am crazy
}
Re: If-Else in C# 80 80

Thanks, Tek. I fixed the problem. I was out of scope for what I wanted to do.

Re: If-Else in C# 80 80

Here is a pretty good reference Dani

C# Corner

Re: If-Else in C# 80 80

I know you fixed it but I recall that C# doesn't allow for boolean values like true and false I'm thinking that was it am I correct?

Re: If-Else in C# 80 80

C# has the bool data type, which allows for true and false. Also another great resource for C# that I really like is http://www.codeproject.com (also has other sections besides C# too)

Re: If-Else in C# 80 80

actually C# depends entirely on bool data types in both selection and loop statements, it does not accept any other types we used to in C++ for example
E.G :
While (1) // it will compile in C++ but it will be a compiler error in C#
{
}

Re: If-Else in C# 80 80

All the C++ would be doing is converting 1 into "true"; that's not rocket science. This would work:

while(Convert.ToBoolean(1)) {}

Re: If-Else in C# 80 80

i didnt say it won't work i was just trying to explain and idea.

Re: If-Else in C# 80 80

It looks to me like you were trying to make a statement and were proven wrong :D

Re: If-Else in C# 80 80

This might sound silly. But I'm working on a C# assignment for school right now, and I can't get a simple if-else statement to work. Isn't the syntax the same as in C++ or Java?

I want to do one thing if a boolean variable is true, something else if it's not. The "bool" type exists in C#, right? ;)

bool bFirsttime;

if (bFirsttime)
{
//code for true condition
}
else
{
//code for false condition

}

Re: If-Else in C# 80 80

alternate shorthand syntax...

txtTest.Text = (txtName.Text == String.Empty) ? "No name" : txtName.Text;

which translates to...

if(txtName.Text == String.Empty)
txtTest.Text = "No name";
else
txtName.Text;

maybe not as readable, but sure saves typing!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.