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"];
Here's one way.
You could also use TryParse
Let us know which way works for you
One possible solution so that you ensure that the DBNull carries across to your code. For our group, as a best practice, we try and not allow NULL columns in the database unless its really needed. There is more overhead in coding to handle it, and sometimes just rethinking the problem makes it so its not required.
While it's convenient to reference
reader["StockValue"]
, it's not very efficient. It's also not strongly-typed, as it returns typeobject
.Instead, within your code, do something like this:
Of course, it's best to get all of the ordinals at one time, then use them throughout the code.
You could do this conversion directly in your DB-query, thus avoiding the special case alltogether.
But I wouldn't call that 'cleaner', unless you can consistently use that form in your code, since you would lose information by returning '0' instead of NULL from the DB.
I have two following extension methods in my project:
The usage can be like this: