2

I'm trying to use the following code to check for a DBNull and set the variable to nothing if it is, or a short if it isn't. The problem is it is failing to set the variable to Nothing and sets it to a 0 instead. Anybody know why?

variable = If(currentRow.Item("variable") Is DBNull.Value,
    Nothing, CShort(currentRow.Item("variable")))

1 Answer 1

5

If variable is declared As Short? then the code works with a slight tweak: you need to cast either operand of If to the target type first:

variable = If(condition, CType(Nothing, Short?), CShort(…))

(You could also have cast the third operand instead, or both.)

This cast is necessary because of how If deduces types: if the two result types mismatch, a common type is deduced which is the closest parent type, i.e. a type from which both inherit. However, with Nothing, new rules come into play because as far as VB is concerned, Nothing is already a valid Short – a default-initialised one (see old answer below for explanation). So VB doesn’t try any type coercion, it simply uses Short as the return value.


Old answer below, assuming that OP had declared variable As Short:

You cannot set value types to Nothing. If you assign Nothing to a value type then it will be set to its type’s default value instead – which is 0 for Short.

You can test this easily:

Dim s as Short = Nothing
Console.WriteLine(s)

Setting a value type to Nothing is the same as invoking its default constructor (New Short()) or declaring a new variable of that type without initialising it. The corresponding operation in C# would be to assign default(T) (short s = default(short)).

If you want to represent null value types, you have to use nullable types:

Dim s as Short? = Nothing

Now s is of type Nullable<Short> (Short? is a shortcut of that) and can be assigned a proper Nothing.

Sign up to request clarification or add additional context in comments.

2 Comments

Right, but my variable is already declared above (should've mentioned that) as "Short?". So, shouldn't this work?
@user1335008 Ah. That changes everything. Wait, let me edit the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.