开发者

VB Check if int is empty

开发者 https://www.devze.com 2023-01-26 12:56 出处:网络
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.

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 ans开发者_开发百科wers on google


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


Maybe what you are looking for is Nullable

    Dim foo As Nullable(Of Integer) = 1
    Dim bar As Nullable(Of Decimal) = 2

    If foo = 1 Then
        If bar = 2 Then
            foo = Nothing
            bar = Nothing
            If foo Is Nothing AndAlso bar Is Nothing Then Stop
        End If
    End If


Well, the default value for a number would be 0, but you can also try this:

int x = 123;
String s = "" + x; 

and then check the length or if the string 's' is empty.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号