a byval-byref-optional-generic oddity

H

Herfried K. Wagner [MVP]

rowe_newsgroups said:
I think it might be helpful for you to take a look at how the compiler
handles setting a value type to 'Nothing'

Take this code for example:

/////////////////
Sub Main()
Dim i As Integer = 5
Console.WriteLine(i)
i = Nothing
Console.WriteLine(i)
Console.Read()
End Sub
/////////////////

If you view the compiled code as VB with reflector it's back to:

////////////////
<STAThread> _
Public Shared Sub Main()
Dim i As Integer = 5
Console.WriteLine(i)
i = 0
Console.WriteLine(i)
Console.Read
End Sub
////////////////

It doesn't actually set the value to 'Nothing' it just knows to reset
the value type back to it's default.

Well, that's exactly what 'Nothing' is used for with value types. You can
compare value type instances with 'Nothing' too: 'If x = Nothing'. Note
that '=' is used instead of 'Is' as 'x' is a variable of a value type. For
user-defined value types, setting the variable to 'Nothing' simply causes a
call to the type's parameterless constructor. That's why value types always
have an implicit parameterless constructor.

\\\
Dim p As Person
p.Age = 22
p = Nothing
MsgBox(p.Age)
///

is IL-equivalent to:

\\\
Dim p As Person
p.Age = 22
p = New Person()
MsgBox(p.Age)
///
This behavior seems to me as just a throw back to the classic days,
a VB specific change (you can't set value types to null in C#) that
was allowed just for upgrading apps and allowing easy upgrading
for classic VB programmers.

Not really. VB6 neiter support setting variables of value types to
'Nothing' nor comparing them with 'Nothing'. Note that in C#
'default(<type>)' can be used instead of 'Nothing' to determine a value
type's default value.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top