why does this execute the else clause

  • Thread starter Thread starter noname
  • Start date Start date
N

noname

char c ='\0';
string cstr = "";
string cstr2;
cstr2 =cstr + c;
//Debugger watch on cstr2.Length shows 0
if( cstr2.Length == 0)
{
MessageBox.Show ("in if",
cstr2,MessageBoxButtons.OKCancel,
MessageBoxIcon.Asterisk);
}
else
{
MessageBox.Show ("in else",
cstr2,MessageBoxButtons.OKCancel,
MessageBoxIcon.Asterisk);
}

why does this execute the else clause
 
noname said:
char c ='\0';
string cstr = "";
string cstr2;
cstr2 =cstr + c;
//Debugger watch on cstr2.Length shows 0
if( cstr2.Length == 0)
{
MessageBox.Show ("in if",
cstr2,MessageBoxButtons.OKCancel,
MessageBoxIcon.Asterisk);
}
else
{
MessageBox.Show ("in else",
cstr2,MessageBoxButtons.OKCancel,
MessageBoxIcon.Asterisk);
}

why does this execute the else clause

Because the string's length isn't 0. It's 1 - it has a single
character, which is the null character. The debugger is showing the
wrong thing here, but the execution is correct.
 
Because cstr2's length is 1. C# strings _can_ contain zeroes; unlike C/C++
strings they're _not_ zero-terminated. (Closest analogy would be BSTRs)
 
noname said:
char c ='\0';
string cstr = "";
string cstr2;
cstr2 =cstr + c;
//Debugger watch on cstr2.Length shows 0

For me, it shows 1. Are you sure you checked the watch *after* that
statement had executed?

The else clause executes because a string containing a null character isn't
an empty string.

P.
 
Paul E Collins said:
For me, it shows 1. Are you sure you checked the watch *after* that
statement had executed?

It could be because the OP is using an unpatch version of VS.NET 2002 -
I seem to remember that there were various bugs when watching strings
in VS.NET 2002.
 
noname said:
char c ='\0';
string cstr = "";
string cstr2;
cstr2 =cstr + c;
//Debugger watch on cstr2.Length shows 0

I have tested this with Borland C#Builder. The watch tells me that
cstr.Length = 1. So there is a bug in the debugger of the compiler that you
use.

Hans Kamp.
 
Tu-Thach said:
The else is executed because cstr2.Length is greater than
0. Maybe something is strange with your debugger.

I think it is, because the debugger of the compiler that I use (C#Builder)
doesn't show this bug, and shows "1" for cstr2.Length.

Hans Kamp.
 
Paul E Collins said:
For me, it shows 1. Are you sure you checked the watch *after* that
statement had executed?

At the start the debugger shows:

cstr2 "null"
cstr2.Length function call terminated by exception

After:

char c ='\0';
string cstr = "";
string cstr2;

it shows:

cstr2 "null"
cstr2.Length function call terminated by exception

After:

cstr2 = cstr + c;

it shows:

cstr ""
cstr2.Length 1

Hans Kamp.
 
Back
Top