Reading data from a database using a DataReader is fast and easy. If something goes wrong, mostly that has to do with null values.
To prevent that, you can extend the DataReader class with some handy methods.

The example below uses the MySqlClient, however, you can use the same methods for SQL and OleDb.
Also, the example only shows methods for integers and strings. Of course you can write similar methods for all data types.


using System;

namespace Utilities
{
    public static class Extentions
    {

        public static int SafeGetInteger(this MySql.Data.MySqlClient.MySqlDataReader reader, string colName)
        {
            int result = 0;
            if (reader[colName]!= null)
            {
                string tmp = reader[colName].ToString();
                if (int.TryParse(tmp, out result))
                {
                    return result;
                }
                else
                {
                    return 0;
                }
            }
            else
            {
                return 0;
            }
            
        }

        public static string SafeGetString(this MySql.Data.MySqlClient.MySqlDataReader reader, string colName)
        {
            if (reader[colName] != null)
                return reader[colName].ToString();
            else
                return string.Empty;
        }
    }
}