(string) reader [0] vs Convert.ToString (reader [0])

what's better

var s = (string)reader[0] 

or

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

?

+6
c # sqldatareader
source share
10 answers

I would say reader.GetString(0)

+7
source share
 // Conveys that you are sure that reader[0] is a string and // if it 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 this is probably a matter of choice, taking into account the context.

+4
source share

If reader [0] is actually a string, then (string)reader[0] .

This is clearer and most likely faster (unless the compiler does some magic optimization, which I don't know about).

+2
source share
 var s = (string)reader[0] 

will give you a class exception if it cannot be written as a string, whereas

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

will handle it more elegantly and you will get null if it cannot be converted. It will also handle more object types for the reader [0], since the other method will only allow clicks in which the type can be wrapped into a string, while it will support any type that the conversion class can handle. I guess this is more. But it may not be ...

+2
source share

This is faster, about ~ 30% faster in my testing:

 var s = (string)reader[0]; 

This, however, will not explode when it is null:

 var s = Convert.ToString(reader[0]); 
+2
source share

How about reader.GetString(0); ?

+2
source share

Why nobody considered readability and maintainability?

I know the author is asking about:

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

But what about:

 string s = reader["Fieldname"].ToString(); 

it is more readable and safer if you change / delete / add columns and the index changes ... it is definitely worth it.

One guy said a hard throw is 30% faster. Okay 30% of 1 ms is 1.333 ms? Of course, not 30% of the entire data sample.

+2
source share

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

+1
source share

What about

reader [0] .ToString ();

+1
source share

I would go with

 reader[0].ToString(); 
0
source share

All Articles