what's better
var s = (string)reader[0]
or
var s = Convert.ToString(reader[0])
?
what's better
var s = (string)reader[0]
or
var s = Convert.ToString(reader[0])
?
If reader[0] is actually a string, then the (string)reader[0]
.
It's clearer and most probably faster (unless the compiler does some magical optimization I don't know about).
var s = (string)reader[0]
will give you a class cast exception if it can't be cast as a string, whereas
var s = Convert.ToString(reader[0])
will handle it more gracefully and you will get null if it can't be converted. This will also handle more types of object for reader[0] as the other method will only allow casts where the type can be cast to a string, whereas this will support any type which the Convert Class can handle. Which I assume is more. But may not be...
This is faster, about ~30% faster in my testing:
var s = (string)reader[0];
This, however, won't blow up when it's null:
var s = Convert.ToString(reader[0]);
// Conveys that you are sure that reader[0] is a string and
// if it's not you probably have bigger problems
// than the resulting exception
var s = (string)reader[0];
// Conveys that you are hoping that reader[0] is convertible to a string
var s = Convert.ToString(reader[0])
So it's probably a matter of choosing taking in consideration the context.
Why did nobody considered the readability and maintainability?
I know the author asks about:
var s = (string)reader[0]
or
var s = Convert.ToString(reader[0])
But what about:
string s = reader["Fieldname"].ToString();
thats more readable and more safe if you exchange/delete/add columns and the index is changing... this is for sure more worth.
One guy said the hard cast is 30% faster. Well 30% of 1 ms are 1,333 ms ? surely not 30% of the whole data fetching.