1

I recently came across two seemingly equivalent ways to get a string from an IDataReader (assume reader implements the IDataReader interface):

reader.GetString(1) reader[4] as string

Why would you use the "array index" method vs the "Get" method? What's the difference between the two approaches?

Adam
  • 8,752
  • 12
  • 54
  • 96
  • 2
    Please do not post screenshots of code, but put [code as text](https://meta.stackoverflow.com/a/285557/2819245) (in a code format block). With regard to possible answers: Those would be basically opinion-based, thus making the question off-topic for StackOverflow (side note: An indexer -with appropriate implementation- could also be used to set/assign a value. With GetString approach, this would require an additional method with a different name/signature like "SetString(index, string)". But this is of course not relevant when being concerned with "get"-like semantics only...) –  May 30 '19 at 19:17
  • The screenshot is gone. However, I don't agree that the answer to this question is entirely opinion-based. The answer to the question "what is the difference between the two approaches" would be based on an understanding of the underlying implementation details of each approach, it's not asking for an opinion RE which approach is better. – Adam May 30 '19 at 20:41
  • As far as I'm aware, there's no major difference in the way it retrieves data. The GetString method just returns the right type so you don't have to assign it. You can also use the reader["name"] approach instead of the array index... which I know your question isn't asking about and you likely already know that. Interested to hear if there's a major difference between the two ways. – KevinLamb May 30 '19 at 21:03

1 Answers1

0

Having looked at the code I pulled the snippet from in more detail, I can see at least one big way that the two approaches differ.

reader.GetString(1) will throw an exception if we can't coerce the data in the second column (at index 1) to a string. reader[4] as string uses the as keyword, and as such if the data in the fifth column (index 4) can't be coerced to a string we just get back null, an exception is not thrown.

Adam
  • 8,752
  • 12
  • 54
  • 96