gabsferreira
gabsferreira

Reputation: 3137

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?

Upvotes: 1

Views: 3226

Answers (4)

Jim Wooley
Jim Wooley

Reputation: 10398

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.

Upvotes: 0

Rolf Bjarne Kvinge
Rolf Bjarne Kvinge

Reputation: 19335

Try this:

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

Upvotes: 0

sloth
sloth

Reputation: 101052

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

Upvotes: 1

Oded
Oded

Reputation: 498982

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.

Upvotes: 4

Related Questions