Tuesday, March 13, 2012

simple if statement executing when its not suppose to

O.k., I've got an if statement that is behaving very oddly. Hopefully, I'm just overlooking something.

Let's say I have a variable called "MyVariable" and it is either empty or defined. The code below executes the first part of the if statement even though I haven't added text to "MyVariable".

string MyVariable;

if (MyVariable != "") {
MyLabel.Text = "write some stuff"
} else {
MyLabel.Text = "the variable was empty, write other stuff"
}

If I just make up some false text about MyVariable, then the first part of the statement doesn't execute, so it works, like this:

string MyVariable;

if (MyVariable == "sadfas") {
MyLabel.Text = "write some stuff"
} else {
MyLabel.Text = "the variable was empty, write other stuff"
}

What's going on?The first code sample (btw, use code tags!), it wouldnt compile in VS.NET because you are using an unassigned variable.

The reason its entering the conditional (MyVariable != "") is because the value is null, not string.Empty ("") .. So, because its null, it enters the condition.
Try poping an
<code>
alert(MyVariable);
<code>
in to see if it really is empty.. I bed it's 'Not Defined' or something..!
The reason is that your string in null, not empty. Change your condition to:

if (MyVariable != null) {

then make it:

if (MyVariable != null && MyVariable.Trim().Length > 0)
{
//now i'm sure its filled with some none whitespace chars.
}
Fantastic, thanks all.

0 comments:

Post a Comment