vb.net - Strange behaviour of the If() statement -


today stumbled upon strange behaviour of vb.net if() statement. maybe can explain why working does, or maybe can confirm bug.

so, have sql database table "testtable" int column "nullablecolumn" can contain null. i'd read out content of column.

so declare variable of type nullable(of integer) matter, open sqlclient.sqldatareader "select nullablecolumn testtable" , use following code content of column:

dim content nullable(of integer)  ...  using reader sqlclient.sqldatareader = ...   content = if(reader.isdbnull(reader.getordinal("nullablecolumn")), nothing, reader.getint32(reader.getordinal("nullablecolumn"))) end using 

but after variable content has value 0, not nothing have expected.

when debugging looks alright, so

  • reader.getordinal("nullablecolumn") delivers correct ordinal position of column (which 0)
  • reader.isdbnull(0) , reader.isdbnull(reader.getordinal("nullablecolumn")) deliver true, since content of column indeed null
  • if(1=2, nothing, "not nothing") delivers string "not nothing"
  • if(1=1, nothing, "not nothing") delivers nothing
  • reader.getint32(reader.getordinal("nullablecolumn")) throws error, since null can't converted integer

so, why variable has value 0?

in vb nothing not same null. if operator must determine type of result based on arguments passed it. nothing, of course, has no type type if operator can return in code int32. if isdbnull method returns true, if operator returns nothing cast int32. in vb, nothing returns default value type. int32, default value 0.

from msdn on nothing keyword:

nothing represents default value of data type. default value depends  on whether variable of value type or of reference type.  non-nullable value types, nothing in visual basic differs null in c#.  in visual basic, if set variable of non-nullable value type nothing,  variable set default value declared type. in c#, if  assign variable of non-nullable value type null, compile-time error  occurs. 

i think regular if work best:

if not reader.isdbnull(reader.getordinal("nullablecolumn"))     content = reader.getint32(reader.getordinal("nullablecolumn")) end if  

or keep shorter

if not reader.isdbnull(reader.getordinal("nullablecolumn")) content = reader.getint32(reader.getordinal("nullablecolumn")) 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -