array-index style vs Get..., retrieving data from an IDataReader in C#

73 Views Asked by At

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?

1

There are 1 best solutions below

0
Adam On

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.