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?
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 astring.reader[4] as stringuses theaskeyword, and as such if the data in the fifth column (index 4) can't be coerced to a string we just get backnull, an exception is not thrown.