Uninitialized variables

  • Thread starter Thread starter Tim Anderson
  • Start date Start date
T

Tim Anderson

Is this expected behavior?

Winform with button and listbox:

Dim i As Integer
For i = 0 To 50
Dim s As String
If i = 1 Then
s = "Only once?"
End If
Me.ListBox1.Items.Add("Test " & s)
Next

If I run this code I find that the value of s remains at
"Only once?" through all the iterations after i=1, although
it is not declared as static.

This is certainly what (might) happen in C with an
uninitialized variable, but I though VB was super-safe and
would automatically initialize variables to a sensible default?

If not, surely the VB compiler should do what the C#
compiler does and check for uninitialized variables?

Tim
 
What version of .NET are you using?

--
HTH,
-- Tom Spink, Über Geek

Please respond to the newsgroup,
so all can benefit

"Maybe it's a game called 'Punish the User'"
 
Hello,

Tim Anderson said:
Is this expected behavior?

Winform with button and listbox:

Dim i As Integer
For i = 0 To 50
Dim s As String
If i = 1 Then
s = "Only once?"
End If
Me.ListBox1.Items.Add("Test " & s)
Next

If I run this code I find that the value of s remains at
"Only once?" through all the iterations after i=1, although
it is not declared as static.

That's IMHO the expected behavior:

\\\
Dim i As Integer
For i = 1 To 2
Dim s As String
If i = 1 Then
s = "Only once?"
End If
MsgBox(s)
Next i
///

Will show "Only once?" two times. Notice that s will _not_ be destroyed and
re-allocated in every iteration of the loop.
This is certainly what (might) happen in C with an
uninitialized variable, but I though VB was super-safe and
would automatically initialize variables to a sensible default?

The variable will persist over the iterations of the loop. Let's have a
look at the code below:

\\\
Dim i As Integer
For i = 1 To 2
Dim s As String = ""
If i = 1 Then
s = "Only once?"
End If
MsgBox(s)
Next i
///

The code above is the same as this:

\\\
Dim i As Integer
For i = 1 To 2
Dim s As String
s = ""
If i = 1 Then
s = "Only once?"
End If
MsgBox(s)
Next i
///

In both cases, 's' will be allocated only one time and will not be destroyed
(OK, assigning a new value to a string variable creates a new string, but
that's not what I want to say).

Regards,
Herfried K. Wagner
 
Tim,

Your string is defined with block scope, where the block is the For/Next
loop. You never leave it, so it doesn't get redefined.

Larry Woods
 
Larry Woods said:
Tim,

Your string is defined with block scope, where the block is the For/Next
loop. You never leave it, so it doesn't get redefined.

Thanks (and to others) for the comments. I notice VB6 is the same.

I still find the logic of this somewhat puzzling. The Dim keyword declares and
allocates storage space for variables. In this situation though, although the
Dim statement is executed on each iteration of the loop, it is only effective
once. However, if I type:

Dim s As String = String.Empty

then the empty string is assigned on each iteration of the loop. However,
if I type:

Static s as String = String.Empty

the assignment only happens once (which is what I would expect).

Tim
 
Hi Tim,

Also, in VB6 there was no concept of Block scope. You will notice that in
VB6 the variable is not re-initialized. In VB.NET we have what is called
Block Scope. Notice that in VB.NET you cannot use the variable 's' outside
of the For/Next loop. Since the scope of 's' is inside of the For/Next and
*not* the procedure it is initialized each time through the For/Next loop.
This is described in:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcn7/html/
vbconscopelevels.asp

The static variable lifetime is different so it doesn't get re-initialized.
Look up lifetime under visual basic language concepts in help and you will
find this explanation:
More stuff on LifeTime:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcn7/html/
vbconlifetime.asp


Regards,
Peter Huang
Microsoft Online Partner Support
Get Secure! www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

--------------------
 
Peter Huang said:
Since the scope of 's' is inside of the For/Next and
*not* the procedure it is initialized each time through the For/Next loop.
This is described in:

But it is *not* initialized each time, as your referenced tech note makes clear:

"Even if the scope of an element is limited to a block, its lifetime is still that
of the entire procedure. If you enter the block more than once during the
procedure, a block variable retains its previous value."

I don't see the logic of this, particularly since if you want this behavior you
can have it via the static declaration (I realise that static is different in that
its value will persist if the procedure is re-entered, but you could reset the
value at the beginning of the procedure).

However I understand how it works now so hopefully it won't catch me
out (I'm a believer in initializing all variables anyway).

Tim
 
Hi Tim,

If you change the code
Static s as String = String.Empty
to
Static s as String
s = String.Empty

Then it will be initialized every time you enter the for-next loop. I think
it is by design.

Regards,
Peter Huang
Microsoft Online Partner Support
Get Secure! www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.

--------------------
From: "Tim Anderson" <[email protected]>
References: <[email protected]>
<[email protected]>
 
Peter,

I don't have any problem getting the code to do what I want,
now that I know what VB does.

I just doubt the logic of it, that's all :-)

Given that VB auto-initializes strings to Nothing, one would think
that:

Dim s as String
and
Dim s as String = Nothing

would be equivalent. But they are not!

Thanks,

Tim
 
Tim,
I am following this thread from the start.(I even have it in a
testsituation) :-)
If string=nothing means in VB.net string exist but have no value
If string Is nothing means in VB.net if string does not exist.
I would find it very unregular if that logic was not followed in your
examles.
Cor
 
Cor said:
Tim,
I am following this thread from the start.(I even have it in a
testsituation) :-)
If string=nothing means in VB.net string exist but have no value
If string Is nothing means in VB.net if string does not exist.
I would find it very unregular if that logic was not followed in your
examles.

Not sure if I fully understand your comment. Consider this code:

Dim s as String = Nothing
Console.WriteLine(s = String.Empty)
Console.WriteLine(isNothing(s))
Console.WriteLine(isNothing(String.Empty))

This outputs:

True
True
False

Is that what you expect? It strikes me as odd.

Tim
 
Tim,
I find it mean from you to mean that what I try to say is mean.
In VB.net we have the Microsoft.Visual Basic commando's and the System.Net
commando's.
That they maybe are look alike doesn't mean they are the same.
Nobody in this thread has spoken about the isNothing function.
But I stop argue with you because it isNothing
I was stupid that I did it not let it be for me Is Nothing.
Succes with others.
Cor
 
Tim Anderson said:
Not sure if I fully understand your comment. Consider this code:

Dim s as String = Nothing
Console.WriteLine(s = String.Empty)
Console.WriteLine(isNothing(s))
Console.WriteLine(isNothing(String.Empty))

This outputs:

True
True
False

Is that what you expect? It strikes me as odd.

- String is a reference type
- String.Empty is a zero-length String.
- When comparing Strings using "=", Nothing is converted to a zero-length
string before comparison (see docs for "=" comparison operator). That's why
the first line returns "True".
 
Cor said:
If string=nothing means in VB.net string exist but have no value

It has the value "" ("empty" string, string of length 0).
If string Is nothing means in VB.net if string does not exist.
I would find it very unregular if that logic was not followed
in your examles.

???
 
Armin Zingler said:
- When comparing Strings using "=", Nothing is converted to a zero-length
string before comparison (see docs for "=" comparison operator). That's why
the first line returns "True".

Well yes, so it seems. I'm not sure though why VB does this.

Tim
 
Herfried,
Normaly I just see to this discussions to have fun, I have them seen so
often and they are as the water in the Donau.
The discussion was about the declaration from strings and what was the logic
behind some things,
But it was moving up and everytime there was a new argument.
When I came in it was about that it was not logic that
string = nothing was equal to string = ""
But in VB is | If String = nothing | something else than | If String Is
nothing|.
Therefore it is logical to keep that logic constant in the language.
What it in another language means is not relevant.

And then came again a new item "IsNothing" which has of course nothing to do
with it.
Or as much as Mid, Len, etc. (just as example not completly)
So I stopped arguing with my standard examples about natural languages.
A word has different meanings, but it has to be posible to evaluate that.
It looks if Tim thinks that a language is a table of mathimatical
instructions.
You know how we think about that.

Cor
ps.
You know of course that mean has minimal 3 different meanings in English.
 
Does what?

This seems logical. = is a comparison operator, 'Is' is an object reference
comparison.

Reference Types pass themselves around as pointers, so if two pointers are
the same, hurrah! same object reference.

'Is' is used for comparing these pointers.
= is used for comparing values.

So, in the case of =, Nothing is a zero-length string, and in the case of
'Is', Nothing is a null reference pointer.

--
HTH,
-- Tom Spink, Über Geek

Please respond to the newsgroup,
so all can benefit

"Maybe it's a game called 'Punish the User'"
 
Cor said:
It looks if Tim thinks that a language is a table of mathimatical
instructions.

Not something I recall saying.
Cor
ps.
You know of course that mean has minimal 3 different meanings in English.

3 words in common usage from different roots. But many different meanings.

Tim
 
Back
Top