简体   繁体   中英

How to really check if something is null in VB.NET?

I have an entity with a NrPeso decimal property that can be saved in the database as 0 or null. Here is what I'm doing to assign the value to the property:

entity.NrPeso = Convert.ToDecimal(object.value("value"))

The problem is: if I don't fill the object value, it's set to Nothing . When I do the cast it turns into 0. But I don't want 0, I want Nothing . If I compare the object value with Nothing it will return me Nothing if it is Nothing or 0.

I tought in a few alternatives but they don't seem good.

So, what is the right way to do this?

Decimal is a structure - is cannot be Nothing by definition.

You need a nullable Decimal .

If NrPeso is defined as Nullable(Of Decimal) (aka Decimal? ), things should work as you expect.

If you want to distinguish between 0 and Nothing when using Decimal (or any other value type), you should use a nullable type in the first place.

So use Decimal? instead of Decimal

Try this:

Dim obj As Object = object.value("value")
entity.NrPeso = If (obj Is Nothing, Nothing, Convert.ToDecimal (obj))

Instead of using Convert.ToDecimal, consider using Decimal.TryParse and then in a failure condition explicitly set the Nullable type to Null:

Dim outVal As Decimal?
If Decimal.TryParse(object.value("value"), outVal)
   entity.NrPeso = outVal
Else
   entity.NrPeso = Nothing
End If

Additionally, consider setting Option Strict On in your project to avoid type issues like this in the future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM