<p>So I'm using an IDataReader to hydrate some business objects, but I don't know at runtime exactly what fields will be in the reader.  Any fields that aren't in the reader would be left null on the resulting object.  How do you test if a reader contains a specific field without just wrapping it in a try/catch?</p>

[{'answer_id': 299772, 'author': 'adparadox', 'author_id': 1962, 'author_profile': 'https://Stackoverflow.com/users/1962', 'pm_score': -1, 'selected': False, 'text': '<p>You can\'t just test reader["field"] for null or DBNull because a IndexOutOfRangeException is thrown if the column isn\'t in the reader.</p>\n\n<p>The code I use in my mapping layer for creating domain objects and the stored procedures that use the mapping layer might have different column names is below; you could modify it to not throw an exception if the column isn\'t found and return default(t) or null.</p>\n\n<p>I understand this isn\'t the most elegant or optimal solution (and really, if you can avoid it then you should), however, legacy stored procedures or Sql queries might warrant a work-around.</p>\n\n<pre><code>    /// &lt;summary&gt;\n    /// Grabs the value from a specific datareader for a list of column names.\n    /// &lt;/summary&gt;\n    /// &lt;typeparam name="T"&gt;Type of the value.&lt;/typeparam&gt;\n    /// &lt;param name="reader"&gt;Reader to grab data off of.&lt;/param&gt;\n    /// &lt;param name="columnNames"&gt;Column names that should be interrogated.&lt;/param&gt;\n    /// &lt;returns&gt;Value from the first correct column name or an exception if none of the columns exist.&lt;/returns&gt;\n    public static T GetColumnValue&lt;T&gt;(IDataReader reader, params string[] columnNames)\n    {\n        bool foundValue = false;\n        T value = default(T);\n        IndexOutOfRangeException lastException = null;\n\n        foreach (string columnName in columnNames)\n        {\n            try\n            {\n                int ordinal = reader.GetOrdinal(columnName);\n                value = (T)reader.GetValue(ordinal);\n                foundValue = true;\n            }\n            catch (IndexOutOfRangeException ex)\n            {\n                lastException = ex;\n            }\n        }\n\n        if (!foundValue)\n        {\n            string message = string.Format("Column(s) {0} could not be not found.",\n                string.Join(", ", columnNames));\n\n            throw new IndexOutOfRangeException(message, lastException);\n        }\n\n        return value;\n    }\n</code></pre>\n'}, {'answer_id': 299789, 'author': 'Craig Wilson', 'author_id': 25333, 'author_profile': 'https://Stackoverflow.com/users/25333', 'pm_score': -1, 'selected': False, 'text': "<p>While I disagree with this approach (I think when accessing data, you should know the shape before hand), I understand that there are exceptions.</p>\n\n<p>You could always load up a datatable with the reader and then iterate through it.  You can then check to see if the column exists. This will be less performant, but you won't need try/catch blocks (so maybe it is more performant for your needs).</p>\n"}, {'answer_id': 1271870, 'author': 'mrrrk', 'author_id': 155791, 'author_profile': 'https://Stackoverflow.com/users/155791', 'pm_score': 3, 'selected': False, 'text': '<p>This should do the trick:</p>\n\n<pre><code>    Public Shared Function ReaderContainsColumn(ByVal reader As IDataReader, ByVal name As String) As Boolean\n        For i As Integer = 0 To reader.FieldCount - 1\n            If reader.GetName(i).Equals(name, StringComparison.CurrentCultureIgnoreCase) Then Return True\n        Next\n        Return False\n    End Function\n</code></pre>\n\n<p>or (in C#)</p>\n\n<pre><code>public static bool ReaderContainsColumn(IDataReader reader, string name)\n{\n    for (int i = 0; i &lt; reader.FieldCount; i++) {\n        if (reader.GetName(i).Equals(name, StringComparison.CurrentCultureIgnoreCase)) return true; \n    }\n    return false;\n}\n</code></pre>\n\n<p>:o)</p>\n'}, {'answer_id': 1271929, 'author': 'Tadmas', 'author_id': 3750, 'author_profile': 'https://Stackoverflow.com/users/3750', 'pm_score': 3, 'selected': False, 'text': '<p>You can also use <code>IDataReader.GetSchemaTable</code> to get a list of all the columns in the reader.</p>\n\n<p><a href="http://support.microsoft.com/kb/310107" rel="noreferrer">http://support.microsoft.com/kb/310107</a></p>\n'}, {'answer_id': 1271952, 'author': 'Seb Nilsson', 'author_id': 2429, 'author_profile': 'https://Stackoverflow.com/users/2429', 'pm_score': 0, 'selected': False, 'text': '<p>The best solution I\'ve used is doing it like this:</p>\n\n<pre><code>DataTable dataTable = new DataTable();\ndataTable.Load(reader);\nforeach (var item in dataTable.Rows) \n{\n    bool columnExists = item.Table.Columns.Contains("ColumnName");\n}\n</code></pre>\n\n<p>Trying to access it through <em>reader["ColumnName"]</em> and checking for null or DBNull will throw an exception.</p>\n'}, {'answer_id': 22367187, 'author': 'Clement', 'author_id': 552183, 'author_profile': 'https://Stackoverflow.com/users/552183', 'pm_score': 2, 'selected': False, 'text': '<pre><code>Enumerable.Range(0, reader.FieldCount).Any(i =&gt; reader.GetName(i) == "ColumnName")\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/52952', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4541/']