Setting a Nullable Integer to a String containing Nothing gives 0

I am pulling my hair due to unexpected behavior from integers with a zero value.

  • If I installed Integerin Nothing, it will become Nothingas expected.
  • If I set Integer?to String, that is Nothing, it will become 0!

Of course, I get this if I explicitly use Stringto Integer?or not.

I understand that I can easily get around this, but I want to know what I am missing.

    Dim NullString As String = Nothing
    Dim NullableInt As Integer? = CType(NullString, Integer?) 'Expected NullableInt to be Nothing, but it 0!
    NullableInt = Nothing 'This works, of course. NullableInt is Nothing. 

EDIT: I used to have code, so without explicitly converting to Integer?, and everything seemed to be fixed / confused about this. There were many suggestions that Option Strict On would catch this type of thing. However, this is actually a fad of rules for converting strings to integers that precede the NULL types, but still affect them.

+3
source share
2 answers

, VB.Net. String Integer? , , . , String Integer. VB.Net Nothing String Integer 0.

Dim local1 As String = Nothing
Dim local2 As Integer = local1 ' It 0

Integer 0 Integer?, Integer.

+6

?

    Dim nullInt As Nullable(Of Integer) 'nullInt = Nothing as expected

    'the following should NOT compile and won't with Option Strict On

    nullInt = ""
    nullInt = String.Empty
0

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


All Articles