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

Why is it 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 
+6
source share
2 answers

Using Option Strict On is a pretty good way to avoid such surprises. You get "what the hell are you trying to do?" error message from the compiler.

But with this Off, these are valid statements performed by DLR, Dynamic Language Runtime. Which is able to appreciate late expressions like this. However, does it have a null type problem of type Integer? . It must deal with a boxed version of the value. It is just nothing. And nothing has any type information associated with it. Nothing can do DLR to see that it started as a whole integer with a zero value, since it all knows that it could be a string that is nothing.

The compiler also cannot help, it cannot emit any code to force the expression to follow normal evaluation rules. All he knows is that there is some function, she does not know who, whose name is "MyFunction", has no idea what value it returns. He passes the dollar to DLR to sort it.

So DLR just shoots him. And he comes up with the sentence “No idea” + 0 = 0. Given that he has type information for 0. This is Integer, so he tries to interpret the left operator as a whole. What really is Nothing is the correct default value for Integer.

Function, not error.

+4
source

Visual Basic.NET had Nothing long before it had NULL value types - it inherited it from pre-.NET Visual Basic. And in some cases, it behaves more like C # default(T) , then t does null .

Your last call calls the AddObject method in Visual Basic Compiler Services. This method exists for a long time and again prescribes value types with zero values ​​and, unfortunately, is poorly documented.

Unfortunately, they cannot lead to the fact that NULL types behave absolutely sequentially, especially in the face of late calls, while maintaining backward compatibility. For example, this also prints 0 :

 Console.WriteLine(CType(CType(Nothing, Object), Int32)) 
+2
source

Source: https://habr.com/ru/post/979848/


All Articles