clweeks
clweeks

Reputation: 875

What's going on with my assignment of Nothing to an Int32?

I have a couple class properties defined like:

Property CustomerKey As Int32
Property ProductStructureHeaderKey As Int32?

At one point in my code, immediately after declaring an instance of that class, I try to set those two values with:

    dps.CustomerKey = row.Cells(2).Value
    dps.ProductStructureHeaderKey = If(row.Cells(1).Value Is Nothing, Nothing, Int32.Parse(row.Cells(1).Value))

My problem is that when the value in row.Cells(1) is Nothing, the ProductStructureHeaderKey ends up equal to 0, not Nothing. And it seems like it should work because this works:

    dps.ProductStructureHeaderKey = Nothing

So that makes me think that I'm actually doing If() wrong, but I use that all the time and can't imagine what's going on.

So...thoughts?


Related to the above, why do I seem to need to Int32.Parse() the value when assigning it to a nullable Int32, but not in the first case?

Upvotes: 1

Views: 74

Answers (1)

Dave Doknjas
Dave Doknjas

Reputation: 6542

'Nothing' in VB means 'default value' of the type in question. In your 'If' statement, VB knows that 'Int32.Parse(row.Cells(1).Value)' is an integer, not a nullable Integer, so it interprets 'Nothing' in the 'If' statements as an integer. 'Nothing' applied to 'Integer' is 0.

You can use:

If(row.Cells(1).Value Is Nothing, CType(Nothing, Integer?), Int32.Parse(row.Cells(1).Value))

A common source of confusion with these sorts of issues is that 'Nothing' in VB is not the same as 'null' in C# - 'Nothing' in VB always has the meaning of "default value" of the type in question.

Upvotes: 3

Related Questions