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
Ultimately it depends on the particular implementation of
System.Data.IDataReaderyou are referring to, but let’s assume you meanSystem.Data.SqlClient.SqlDataReader.In this case,
reader[i]andreader.GetValue(i)do exactly the same thing. In fact,reader[i]internally callsreader.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 isobject). 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 astring. If the value in that column is not astring, anInvalidCastExceptionwill be thrown. Use this method when you are sure that the value is astringandstringis 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.IDataReadershould behave in the same way.