Object behaviour of simple data types?
-
Hi all, In .NET all data types (Integer, Long, String, ...) are objects. But in my opinion, these data types don't really behave like normal objects. I noticed the following behaviour:
Dim l As Long Msgbox(l = Nothing) 'Results in True Msgbox(l = 0) 'Results in True
Even stranger behaviour:Dim l As Long l = 0 Msgbox(l = Nothing) 'Results in True
I hoped that in .NET there would be a way to determine if a variable has been set or not. For example you have a class with a ID property (long), you would implement it like this:Public Class Test Private _id As Long Public Property ID As Long Get Return _id End Get Set(Value As Long) _id = Value End Set End Property End Class
Suppose you would like to have functionality in this class, to save the data. In de Save sub, you would like to check if the ID property was set or not. I hoped you could do it like this:Public Sub Save If _id = Nothing Then 'Raise error to tell the ID property was not set. Else 'Save data End If End Save
Was it wrong of me to expect such behaviour, or am I wrong somewhere? Thanks, Jan -
Hi all, In .NET all data types (Integer, Long, String, ...) are objects. But in my opinion, these data types don't really behave like normal objects. I noticed the following behaviour:
Dim l As Long Msgbox(l = Nothing) 'Results in True Msgbox(l = 0) 'Results in True
Even stranger behaviour:Dim l As Long l = 0 Msgbox(l = Nothing) 'Results in True
I hoped that in .NET there would be a way to determine if a variable has been set or not. For example you have a class with a ID property (long), you would implement it like this:Public Class Test Private _id As Long Public Property ID As Long Get Return _id End Get Set(Value As Long) _id = Value End Set End Property End Class
Suppose you would like to have functionality in this class, to save the data. In de Save sub, you would like to check if the ID property was set or not. I hoped you could do it like this:Public Sub Save If _id = Nothing Then 'Raise error to tell the ID property was not set. Else 'Save data End If End Save
Was it wrong of me to expect such behaviour, or am I wrong somewhere? Thanks, JanFirst, you can't check for null references with
If x = Nothing ...
- you have to useIf x **Is** Nothing ...
Second, you can't perform reference comparison on value types. Ifx
is a value type,If x Is Nothing ...
will not compile. Try something like:Public Class Test
Private _id As Long
Private _idSet As Boolean = FalsePublic Property ID As Long Get Return \_id End Get Set(ByVal Value As Long) \_id = Value \_idSet = True End Set End Property Public Sub Save() If \_idSet Then 'Save Data Else 'Throw exception End If End Sub
End Class