views:

379

answers:

10

what's better

var s =  (string)reader[0]  

or

var s = Convert.ToString(reader[0])

?

+1  A: 

I would guess reader[0].ToString();

sshow
+2  A: 

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).

Dave Markle
+1  A: 

what about

reader[0].ToString();

Asad Butt
+2  A: 
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...

Sam Holder
+6  A: 

I'd say reader.GetString(0)

Joel Coehoorn
Circra release of NETFX 2 I did lots of research and found the Get<T> methods with the indexed looked was the best performing of all reader methodologies.
keithwarren7
I have also measured this in 3.5 and found that this performed measurably better than `(string)reader[0]`.
mquander
+2  A: 

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]);
Nick Craver
+2  A: 

How about reader.GetString(0);?

shahkalpesh
+4  A: 
// 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.

João Angelo
+1 for considering the readability and intent of the code, and not just performance.
rob
A: 

I would go with

reader[0].ToString();
Andrew
+1  A: 

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.

Lisa
This answer should be heeded.
Jason