0 = Nothing

jigga77

New member
Joined
Apr 18, 2006
Messages
3
Programming Experience
Beginner
Hello All,

Just a beginners question:

Why is zero the same as Nothing, I thought zero was een int32 object so it cannot be nothing .....right...?

Dim MyInt as int32 = 0

if MyInt = Nothing then
Console.WriteLine("You are stupid, 0(Zero) = the same as Nothing")
else
Console.WriteLine("You are NOT stupid because 0(Zero) is not the same as Nothing")

Could somebody please explain this to me !?
 
In your visual basic.net main window, select HELP from menu bar, select SEARCH, then search for 'Nothing'. You'll find it is the default value for any data type. So zero sounds Ok for a default, eh?
 
Interesting Question ... it seems like Visual Basic.NET actually says that if you set a value type instance to nothing, it actually sets the value of that type to its default as well if you set it to null (same rule) In this case, the default value of a myInt instance is the null which is same with nothing.
But, don't you think you shouldn't care much about this?
 
jimmajsterski, you are right.

Nothing = Default Value (=0 for int)

But i was expecting that nothing was a kind of null reference

I'm asking because i'v have these omjects with an ID and a save(to database) method, in the save method I wanted to check if an ID = nothing in which case it is een new object so I have to get a new ID and if ID <> nothing it is an existing object and I need to update

But since ID = an int the first object with an ID of 0 is always getting added again.

Protected Function EntitySave() As Boolean
If Not Me.Id = Nothing Then
Return Me.Add()
Else
Return Me.Update()
End If
End Function
 
(..default value for any data type, funny, thought we rid any by vb6 :p )

I think you are perhaps mixing value types which are not nullable and references types that are nullable. See the help topic for explanation why.

However, you can create nullables (of value types) that take their regular type value range in addition to null value.
VB.NET:
Dim i As Nullable(Of Integer)
MsgBox("value of i is :" & i.ToString)
If i.HasValue = False Then MsgBox("i has not a value")
 
i = Nothing
MsgBox("value of i is :" & i.ToString)
If i.HasValue = True Then MsgBox("i has a value?")
 
i = 0
MsgBox("value of i is :" & i.ToString)
If i.HasValue = True Then MsgBox("now i has a value")
 
Back
Top