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")))
If
variableis declaredAs Short?then the code works with a slight tweak: you need to cast either operand ofIfto the target type first:(You could also have cast the third operand instead, or both.)
This cast is necessary because of how
Ifdeduces 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, withNothing, new rules come into play because as far as VB is concerned,Nothingis already a validShort– a default-initialised one (see old answer below for explanation). So VB doesn’t try any type coercion, it simply usesShortas the return value.Old answer below, assuming that OP had declared
variable As Short:You cannot set value types to
Nothing. If you assignNothingto a value type then it will be set to its type’s default value instead – which is0forShort.You can test this easily:
Setting a value type to
Nothingis 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 assigndefault(T)(short s = default(short)).If you want to represent
nullvalue types, you have to use nullable types:Now
sis of typeNullable<Short>(Short?is a shortcut of that) and can be assigned a properNothing.