Search code examples
vb.netintegervalue-type

VB Check if int is empty


A really boring question, sorry, but I really don't know that yet ;) I've tried always string.empty, but with a decimal this produces an error.

Is there any function? Unfortunately, for the simplest questions, there are no answers on google


Solution

  • Your title (and tag) asks about an "int", but your question says that you're getting an error with a "decimal". Either way, there is no such thing as "empty" when it comes to a value type (such as an Integer, Decimal, etc.). They cannot be set to Nothing as you could with a reference type (like a String or class). Instead, value types have an implicit default constructor that automatically initializes your variables of that type to its default value. For numeric values like Integer and Decimal, this is 0. For other types, see this table.

    So you can check to see if a value type has been initialized with the following code:

    Dim myFavoriteNumber as Integer = 24
    If myFavoriteNumber = 0 Then
        ''#This code will obviously never run, because the value was set to 24
    End If
    
    Dim mySecondFavoriteNumber as Integer
    If mySecondFavoriteNumber = 0 Then
        MessageBox.Show("You haven't specified a second favorite number!")
    End If
    

    Note that mySecondFavoriteNumber is automatically initialized to 0 (the default value for an Integer) behind the scenes by the compiler, so the If statement is True. In fact, the declaration of mySecondFavoriteNumber above is equivalent to the following statement:

    Dim mySecondFavoriteNumber as Integer = 0
    


    Of course, as you've probably noticed, there's no way to know whether a person's favorite number is actually 0, or if they just haven't specified a favorite number yet. If you truly need a value type that can be set to Nothing, you could use Nullable(Of T), declaring the variable instead as:

    Dim mySecondFavoriteNumber as Nullable(Of Integer)
    

    And checking to see if it has been assigned as follows:

    If mySecondFavoriteNumber.HasValue Then
        ''#A value has been specified, so display it in a message box
        MessageBox.Show("Your favorite number is: " & mySecondFavoriteNumber.Value)
    Else
        ''#No value has been specified, so the Value property is empty
        MessageBox.Show("You haven't specified a second favorite number!")
    End If