c# - Why do 'Convert.ToInt32' and 'as int?' work differently? -


convert.toint32(mycommand.executescalar()); // returns 100, because mycommand sql command gets non-null bigint cell mycommand.executescalar() int? ?? 0; //returns 0 when mycommand sql command gets non-null bigint cell 

i have use second way in case, because mycommand.executescalar() can return dbnull. why second way return different result convert.toint32?

edit: thank you, all. changed type int64 , it's working now.

converting , casting (with cast operator, is operator , as operator) 2 different things:

  • convert changing 1 type type. string or int64 int32.
  • casting can done base type inheriting type. in case object int32. object must contain int32 succeed. in case not , cast return null.

in code:

int64 l = 100; object o = l; int32 i1 = o int32? ?? 0; // cast fails, "as" return 0. "??" make 0. int32 i2 = convert.toint32(o); // int32 inside object converted int32 , return 100. 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -