Is there a better/cleaner way to do this?
int stockvalue = 0;
if (!Convert.IsDBNull(reader["StockValue"]))
stockvalue = (int)reader["StockValue"];
Is there a better/cleaner way to do this?
int stockvalue = 0;
if (!Convert.IsDBNull(reader["StockValue"]))
stockvalue = (int)reader["StockValue"];
The shortest (IMHO) is:
Explanation:
Yes you can use
int?
This way you can have a default value of null instead of 0. Since the result of stockvalue could potentially be 0 there isn't confusion as to whether the database was 0 or null. For instance like this (pre nullable) we had a default initialization of -1 to represent no value was assigned. Personally, I thought this was a little dangerous because if you forget to set it to -1, there is a data corruption issue that can be really difficult to track down.http://msdn.microsoft.com/en-us/library/2cf62fcy(VS.80).aspx
use the
Nullable<int>
type...int?
for shortI wrote an extension method several days ago. By using it you could just do:
Here's the extension method (modify to fit your needs):
Not really. You could encapsulate it in a method:
And call it like this:
Or you could use
coalesce
in your query to force the returned value to be non-null.Edit - corrected dumb code errors based on comments received.