Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataReader[i] vs DataReader.GetValue(i) vs DataReader.GetString(i)

Is

dataReader[i]

logically equivalent to

dataReader.GetValue(i)

Are they the same? Are they different? Is there a situation where one would be appropriate over the other?

There are documented differently:

  • Gets the column located at the specified index
  • Return the value of the specified field.

But when i use them they both return the value of the field. What does it mean to "get the column"? What does it mean to "return the value of a field"?


Bonus Chatter:

When I call:

reader[i];
reader.GetValue(i);
reader.GetString(i);

i get a String each time

like image 263
Ian Boyd Avatar asked Dec 08 '11 20:12

Ian Boyd


1 Answers

Ultimately it depends on the particular implementation of System.Data.IDataReader you are referring to, but let's assume you mean System.Data.SqlClient.SqlDataReader.

In this case, reader[i] and reader.GetValue(i) do exactly the same thing. In fact, reader[i] internally calls reader.GetValue(i). (You can see this by disassembling the code using a tool like ILSpy.). Both these members return the value in the i-th column of the current row and will return successfully regardless of the type of the value (the return type is object). The documentation for both of these members is a little misleading and could be worded in a better way. You can use either of these members wherever you like, just pick the one which you feel reads better.

Whereas reader.GetString(i) is specifically designed to return the value contained in the i-th column of the current row as a string. If the value in that column is not a string, an InvalidCastException will be thrown. Use this method when you are sure that the value is a string and string is the type that you want to work with. This will make your code more concise since you won't have to perform a cast.

In your specific case, the value in the i-th column of the current row must be of type string, which is why the return value of all three members is identical.

If written correctly, other implementations of System.Data.IDataReader should behave in the same way.

like image 187
Adam Ralph Avatar answered Oct 04 '22 20:10

Adam Ralph