473,320 Members | 2,112 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Single-Line If Statement Problem

I have the following single-line if statement that is evaluating true even
though it shouldn't. I have never seen this before and I am concerned that
this can happen in other areas of my code.

If String1.Length > 0 Then String2 = String1

where String1 = ""

This statement also evaluates as true when String1 = "":

If String1 <> "" Then String2 = String1

Changing the If statement to a multi-line If statement corrects the problem:

If String1.Length > 0 Then
String2 = String1
End If

Has anyone else seen this problem or know what's going on?

Thanks
Jul 21 '05 #1
6 8139
Using Single-Line If statements is a bad practice. If programming correctly
solves the problem, then what's the problem?

Bob Lehmann

"DLP22192" <DL******@discussions.microsoft.com> wrote in message
news:06**********************************@microsof t.com...
I have the following single-line if statement that is evaluating true even
though it shouldn't. I have never seen this before and I am concerned that this can happen in other areas of my code.

If String1.Length > 0 Then String2 = String1

where String1 = ""

This statement also evaluates as true when String1 = "":

If String1 <> "" Then String2 = String1

Changing the If statement to a multi-line If statement corrects the problem:
If String1.Length > 0 Then
String2 = String1
End If

Has anyone else seen this problem or know what's going on?

Thanks

Jul 21 '05 #2
Can you give us a complete (short) program that demonstrates the problem?
"DLP22192" <DL******@discussions.microsoft.com> wrote in message
news:06**********************************@microsof t.com...
I have the following single-line if statement that is evaluating true even
though it shouldn't. I have never seen this before and I am concerned
that
this can happen in other areas of my code.

If String1.Length > 0 Then String2 = String1

where String1 = ""

This statement also evaluates as true when String1 = "":

If String1 <> "" Then String2 = String1

Changing the If statement to a multi-line If statement corrects the
problem:

If String1.Length > 0 Then
String2 = String1
End If

Has anyone else seen this problem or know what's going on?

Thanks

Jul 21 '05 #3
I don't buy it. I stepped through the code below, and none of the conditions
evaluated to true. Your description of the problem is leaving something out.
Dim s1 As String
Dim s2 As String
s1 = ""
s2 = "x"
If s1.Length > 0 Then s2 = s1
s2 = "x"
If s1 <> "" Then s2 = s1
s2 = "x"
If s1.Length > 0 Then
s2 = s1
End If
"DLP22192" wrote:
I have the following single-line if statement that is evaluating true even
though it shouldn't. I have never seen this before and I am concerned that
this can happen in other areas of my code.

If String1.Length > 0 Then String2 = String1

where String1 = ""

This statement also evaluates as true when String1 = "":

If String1 <> "" Then String2 = String1

Changing the If statement to a multi-line If statement corrects the problem:

If String1.Length > 0 Then
String2 = String1
End If

Has anyone else seen this problem or know what's going on?

Thanks

Jul 21 '05 #4
Oooooh, Oooooh, I do!

What you are seeing is the VB.Net equivalent of an optical illusion. To
demonstrate -

Try this:

Dim _string1 As String

Console.WriteLine(_string1 Is Nothing)

Console.WriteLine(_string1 = "")

Console.WriteLine(_string1.Length = 0)

The results should be:

True
True
Exception (Object reference not set to an instance of an object)

"But,", I hear you ask, "if the 3rd Console.WriteLine threw an exception
then why didn't the 2nd Console.WriteLine throw an exception also?".

Good question. I don't fully understand why, but if you 'query' the value of
an uninitialised variable whose Type is a 'Value Type' then the value
returned is default value for that Type, but the variable itself stays
uninitialised.

Now try:

Dim _string1 As String = String.Empty

Console.WriteLine(_string1 Is Nothing)

Console.WriteLine(_string1 = "")

Console.WriteLine(_string1.Length = 0)

The results should be:

False
True
True

This is what we we would expect for an initialised string variable. The
variable is initialised so it is not Nothing, it's value is an empty string
and it's length is 0.

What you don't show us is the code that initialised your String1 variable,
but I will bet that it was initialised from a array of bytes or something
like that.

The ASCII characters in the range 0 to 31 can cause unexpected problems for
the uninitiated, especially the NUL character (ASCII 0) which can be
represented by the ControlChars.NullChar constant.

If you 'look' at a string that contains one or more of these, you will only
'see' the characters that precede the first instance of it.

Try this:

Dim _string1 As String = "abc" & ControlChars.NullChar & "def"
Console.WriteLine(_string1.Length)

Console.WriteLine(_string1)

While one might expect to see the results displayed as

6
abcdef

The actual results will be:

7
abc

Note that everything after the NUL character has been suppressed.

Now try:

Dim _string1 As String = ControlChars.NullChar

Console.WriteLine(_string1.Length)

Console.Writeline(_string1 = "")

Console.WriteLine(_string1)

The result is:

1
False

The 2nd Console.Writeline appears to have got it wrong because the 3rd one
displayed a blank line. In fact, the 3rd one only appeared to display a
blank line - it actually displayed nothing at all because of the NUL
character.

NUL character often find their way into strings that have been 'loaded' from
byte arrays but the NUL character is also often used as a delimiter.

If you suspect that there might be NUL characters in a string then you must
handle them correctly.

One way to get get rid of leading and/or trailing NUL characters is to use:

_string1 = string1.Trim(ControlChars.NullChar)

One way to get get rid of imbedded NUL characters is to use:

_string1 = _string1.Replace(ControlChars.NullChar, String.Empty)

The conclusion is that you should never assume that a string varaible has
any given value.

Test, Test, Test!
"DLP22192" <DL******@discussions.microsoft.com> wrote in message
news:06**********************************@microsof t.com...
I have the following single-line if statement that is evaluating true even
though it shouldn't. I have never seen this before and I am concerned
that
this can happen in other areas of my code.

If String1.Length > 0 Then String2 = String1

where String1 = ""

This statement also evaluates as true when String1 = "":

If String1 <> "" Then String2 = String1

Changing the If statement to a multi-line If statement corrects the
problem:

If String1.Length > 0 Then
String2 = String1
End If

Has anyone else seen this problem or know what's going on?

Thanks

Jul 21 '05 #5
Stephany Young <noone@localhost> wrote:
Oooooh, Oooooh, I do!

What you are seeing is the VB.Net equivalent of an optical illusion. To
demonstrate -

Try this:

Dim _string1 As String

Console.WriteLine(_string1 Is Nothing)

Console.WriteLine(_string1 = "")

Console.WriteLine(_string1.Length = 0)

The results should be:

True
True
Exception (Object reference not set to an instance of an object)

"But,", I hear you ask, "if the 3rd Console.WriteLine threw an exception
then why didn't the 2nd Console.WriteLine throw an exception also?".
That's because VB.NET has overloaded the = operator for strings, and
when comparing strings, considers null (Nothing) and the empty string
as being the same. (It doesn't strike me as a good thing, but there we
go.) Here's part of the specs (from section 11.14, Relational
Operators):

<quote>
String. The operators return the result of comparing the two values
using either a binary comparison or a text comparison. The comparison
used is determined by the compilation environment and the Option
Compare statement. A binary comparison determines whether the numeric
Unicode value of each character in each string is the same. A text
comparison does a Unicode text comparison based on the current culture
in use on the .NET Framework. When doing a string comparison, a null
reference is equivalent to the string literal "".
</quote>
Good question. I don't fully understand why, but if you 'query' the value of
an uninitialised variable whose Type is a 'Value Type' then the value
returned is default value for that Type, but the variable itself stays
uninitialised.
Note that string isn't a value type, by the way.

<snip>
Try this:

Dim _string1 As String = "abc" & ControlChars.NullChar & "def"
Console.WriteLine(_string1.Length)

Console.WriteLine(_string1)

While one might expect to see the results displayed as

6
abcdef

The actual results will be:

7
abc

Note that everything after the NUL character has been suppressed.


Not on my box. On mine I get:

7
abc def

(which is what I'd expect).

There used to be a bug in the debugger which would terminate strings on
null characters, and certainly various GUI elements assume null
termination, but the console doesn't.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Jul 21 '05 #6
I stand educated :)

And, yes, I was running my examples in the IDE (Debug) rather than a
console.
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Stephany Young <noone@localhost> wrote:
Oooooh, Oooooh, I do!

What you are seeing is the VB.Net equivalent of an optical illusion. To
demonstrate -

Try this:

Dim _string1 As String

Console.WriteLine(_string1 Is Nothing)

Console.WriteLine(_string1 = "")

Console.WriteLine(_string1.Length = 0)

The results should be:

True
True
Exception (Object reference not set to an instance of an object)

"But,", I hear you ask, "if the 3rd Console.WriteLine threw an exception
then why didn't the 2nd Console.WriteLine throw an exception also?".


That's because VB.NET has overloaded the = operator for strings, and
when comparing strings, considers null (Nothing) and the empty string
as being the same. (It doesn't strike me as a good thing, but there we
go.) Here's part of the specs (from section 11.14, Relational
Operators):

<quote>
String. The operators return the result of comparing the two values
using either a binary comparison or a text comparison. The comparison
used is determined by the compilation environment and the Option
Compare statement. A binary comparison determines whether the numeric
Unicode value of each character in each string is the same. A text
comparison does a Unicode text comparison based on the current culture
in use on the .NET Framework. When doing a string comparison, a null
reference is equivalent to the string literal "".
</quote>
Good question. I don't fully understand why, but if you 'query' the value
of
an uninitialised variable whose Type is a 'Value Type' then the value
returned is default value for that Type, but the variable itself stays
uninitialised.


Note that string isn't a value type, by the way.

<snip>
Try this:

Dim _string1 As String = "abc" & ControlChars.NullChar & "def"
Console.WriteLine(_string1.Length)

Console.WriteLine(_string1)

While one might expect to see the results displayed as

6
abcdef

The actual results will be:

7
abc

Note that everything after the NUL character has been suppressed.


Not on my box. On mine I get:

7
abc def

(which is what I'd expect).

There used to be a bug in the debugger which would terminate strings on
null characters, and certainly various GUI elements assume null
termination, but the console doesn't.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Jul 21 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: sinister | last post by:
The examples in the online manual all seem to use double quotes, e.g. at http://us3.php.net/preg_replace Why? (The behavior is different with single quotes, and presumably simpler to...
4
by: Greg | last post by:
I keep getting an error when I have a tick mark in a text value that I am searching for in my XPath Query. Example: <Authors> <Author LastName="O'Donnel"> <Author LastName="Smith">...
3
by: Bill | last post by:
I have a seating chart web form that has over 50 entry field controls (tables/booths) where I use a DropDownList box to select a single company name from a single large list of organizations (200...
2
by: John Dann | last post by:
I'm retrieving some columns from a database with numeric values that fall comfortably within the range of the Single type and I'm tempted to use Single for the relevant column type in the retrieved...
7
by: ashley.ward | last post by:
We have been using VB6 to develop small custom apps that access an Oracle database, in order to extend a larger product that is developed by our colleagues in Germany (who use C++ and Java). As...
3
by: Eric Layman | last post by:
Hi, I've saved data into the db by doing a replace() on single quote. Right now on data display on a datagrid, it shows double single quote. How do I make changes during run time of datagrid...
8
by: Grant Edwards | last post by:
I'm pretty sure the answer is "no", but before I give up on the idea, I thought I'd ask... Is there any way to do single-precision floating point calculations in Python? I know the various...
4
by: fniles | last post by:
I am looping thru DataReader and constructing a sql query to insert to another database. When the data type of the field is string I insert the field value using a single quote. When the value of...
2
by: Reporter | last post by:
I got the following example from http://www.evolt.org/article/User_Friendly_Forms_in_PHP/20/60144/index.html : echo '<tr><td>First name:</td><td><input type="text" name="first_name"...
0
by: Atos | last post by:
SINGLE-LINKED LIST Let's start with the simplest kind of linked list : the single-linked list which only has one link per node. That node except from the data it contains, which might be...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.