Take the 2-minute tour ×

I'm writing a code that selects data from a database, store it in a DataTable, do some hard math, and updates the database back.

The main issue is that it requires a lot of casting due to DataRow collections returns columns as the object type, forcing me to do float.parse() every single row and making it time-consuming.

Do you guys have any suggestions on how I can avoid this?

Thanks in advance.

share|improve this question
That's not casting what you mention. It's parsing/conversion of a string to a numeric data type. –  Noldorin Sep 23 '11 at 21:42
Are they coming back from the database as floats? Could you just do (float)row["column"] instead of float.parse(row["column"])? Not sure what the difference will turn out to be but might be worth a quick shot. –  John Sep 23 '11 at 21:42
float.parse is not casting: casting is quite fast –  user166390 Sep 23 '11 at 21:42
What library are you using for data access? Can't you do something like reader.GetFloat()? –  alexn Sep 23 '11 at 21:43
sorry for the lack of information, doing (float)object does not work, I have to parser it. –  Lucas Thadeu Sep 23 '11 at 21:44
show 3 more comments

3 Answers

float.Parse is not the same as casting. You should be able to actually cast the value, e.g. one of

(float) row["Foo"]
(double) row["Foo"]
(decimal) row["Foo"]

depending on the type. That will avoid doing any reparsing - you're just unboxing. You may need to unbox and cast if the value isn't in the type you want, e.g.

(float) (double) row["Foo"]

It's unclear exactly how you're using the DataTable, but I would suggest creating your own model class which represents a row of a table in a strongly-typed way, with conversions to and from DataRow - or use a strongly-typed DataSet to start with. That way your code will be a lot clearer, and you'll only need to perform conversions for a small part of your code.

share|improve this answer
add comment

forcing me to do float.parse() every single row

If you need float.parse(), you're doing something wrong somewhere. You should be storing the column in numeric type (float, numeric, decimal, money, etc) rather than a string type (char, varchar, nvarchar, etc), and if you're doing that the value in the datarow column already is a type such that you can use a simple (float) cast (and maybe a check for DBNull).

float.parse() is doubly bad, because not only do you have to parse the value from a string, but you have to first create the string to parse... you're paying for this twice.

share|improve this answer
add comment

If your database returns floats, you don't have to use float.parse. Assuming you have a DataRow row, you can just use something like this:

float val = (float)row["column"];
share|improve this answer
add comment

Your Answer


