473,574 Members | 2,294 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 8164
Using Single-Line If statements is a bad practice. If programming correctly
solves the problem, then what's the problem?

Bob Lehmann

"DLP22192" <DL******@discu ssions.microsof t.com> wrote in message
news:06******** *************** ***********@mic rosoft.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******@discu ssions.microsof t.com> wrote in message
news:06******** *************** ***********@mic rosoft.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.WriteLi ne(_string1 Is Nothing)

Console.WriteLi ne(_string1 = "")

Console.WriteLi ne(_string1.Len gth = 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.WriteLi ne threw an exception
then why didn't the 2nd Console.WriteLi ne 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.WriteLi ne(_string1 Is Nothing)

Console.WriteLi ne(_string1 = "")

Console.WriteLi ne(_string1.Len gth = 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.Nu llChar 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.Nu llChar & "def"
Console.WriteLi ne(_string1.Len gth)

Console.WriteLi ne(_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.Nu llChar

Console.WriteLi ne(_string1.Len gth)

Console.Writeli ne(_string1 = "")

Console.WriteLi ne(_string1)

The result is:

1
False

The 2nd Console.Writeli ne 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(Co ntrolChars.Null Char)

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

_string1 = _string1.Replac e(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******@discu ssions.microsof t.com> wrote in message
news:06******** *************** ***********@mic rosoft.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@localhos t> 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.WriteLi ne(_string1 Is Nothing)

Console.WriteLi ne(_string1 = "")

Console.WriteLi ne(_string1.Len gth = 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.WriteLi ne threw an exception
then why didn't the 2nd Console.WriteLi ne 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.Nu llChar & "def"
Console.WriteLi ne(_string1.Len gth)

Console.WriteLi ne(_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.co m>
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.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Stephany Young <noone@localhos t> 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.WriteLi ne(_string1 Is Nothing)

Console.WriteLi ne(_string1 = "")

Console.WriteLi ne(_string1.Len gth = 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.WriteLi ne threw an exception
then why didn't the 2nd Console.WriteLi ne 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.Nu llChar & "def"
Console.WriteLi ne(_string1.Len gth)

Console.WriteLi ne(_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.co m>
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
8256
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 understand.)
4
31203
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"> </Authors>
3
3509
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 plus conference attendees). All web form datavalues will be one of the same 200 organizations in this list. I would like to avoid creating 50...
2
9730
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 dataset. (Actually the values are held as integers in the database for compact storage but are scaled to their true Single values during...
7
12227
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 each app is small and simple, we have been distributing each to the customer in the form of a single EXE file. I have been attempting to build...
3
2730
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 so that the double single quote will be replaced as single quote? Pls advise.
8
10390
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 array modules generally support arrays of single-precision floats. I suppose I could turn all my variables into single-element arrays, but that would...
4
6238
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 the field has a single quote in it like "O'Toole", how can I construct the string ? Do While drSQL.Read sSQL = "insert into " & sTableName & "...
2
2871
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" value="'.htmlspecialchars($_POST).'"></td></tr>'; What purpose do the single quotes serve in value="'.htmlspecialchars($_POST).'" I don't mean the single...
0
8615
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 anything from a short integer value to a complex struct type, also has a pointer to the next node in the single-linked list. That pointer will be NULL...
0
7826
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7741
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8085
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7838
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6491
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5328
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3781
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2257
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1362
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.