Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between adding zero to nothing in Visual Basic.Net?

Why is this different?!

Public Class Form1
 Public Function MyFunction() As Integer?
    Return Nothing
 End Function

 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim o As Object = Me
    MsgBox(TypeName(Me)) ' Form1
    MsgBox(TypeName(o))  ' Form1
    MsgBox(TypeName(Me.MyFunction())) ' Nothing
    MsgBox(TypeName(o.MyFunction()))  ' Nothing
    ' but
    MsgBox(TypeName(Me.MyFunction() + 0)) ' Nothing
    MsgBox(TypeName(o.MyFunction() + 0))  ' Integer
 End Sub
End Class
like image 404
Babak A Avatar asked Dec 18 '14 11:12

Babak A


People also ask

What is nothing in Visual Basic?

Nothing represents the default value of a data type. The default value depends on whether the variable is of a value type or of a reference type. A variable of a value type directly contains its value. Value types include all numeric data types, Boolean , Char , Date , all structures, and all enumerations.


1 Answers

Using Option Strict On is a pretty good way to avoid surprises like this. You'll get a "what the heck are you trying to do?" error message from the compiler.

But with it Off, these are valid statements, executed by the DLR, the Dynamic Language Runtime. Which is capable of evaluating late-bound expressions like this. It however has a problem with a nullable type like Integer?. It needs to deal with the boxed version of the value. Which is just plain Nothing. And Nothing doesn't have any type information associated with it. There's nothing the DLR can do to see that this started life as a nullable integer, for all it knows it could be a string that is Nothing.

The compiler cannot help either, it cannot emit any code to make the expression follow normal evaluation rules. All it knows is that there is some function, it doesn't know which, whose name is "MyFunction" with no idea what kind of value it returns. It passes the buck to the DLR to sort it out.

So the DLR just punts at it. And it comes up with "No idea" + 0 = 0. Given that it does have type information for 0. It is an Integer so it tries to interpret the left operator as an integer as well. Which is valid, Nothing is a correct default value for Integer.

Feature, not a bug.

like image 130
Hans Passant Avatar answered Sep 19 '22 07:09

Hans Passant