Wednesday 2 November 2011

Reading the value from DataReader

        Use this method to fetch the value from data reader object. It offers you the ability of:

  • Getting the value of built-in data types like Integer, Float, Boolean, String, DateTime etc.
  • Getting the value of built-in enum types like FileMode, StringComparison etc.
  • Getting the value of custom enum types like Gender, Status etc.
  • If reader has the value as DBNull then it returns the Default value corresponding to given type. In case of string, String.Empty is returned.
  • Casting is type safe and optimized.

        /// <summary>
        /// Returns the value from the reader of specified column name and type.
        /// </summary>
        /// <typeparam name="T">Type of the column</typeparam>
        /// <param name="reader">DataReader object</param>
        /// <param name="columnName">Name of the column</param>
        /// <returns>Value of specified type including enum</returns>
        public T GetValue<T>(IDataReader reader, string columnName)
        {
            // Get the position of column in data reader
            int index = reader.GetOrdinal(columnName);
 
            return GetValue<T>(reader, index);
        }
 
        /// <summary>
        /// Returns the value from the reader of specified column index and type.
        /// </summary>
        /// <typeparam name="T">Type of the column</typeparam>
        /// <param name="reader">DataReader object</param>
        /// <param name="columnIndex">Index of the column</param>
        /// <returns>Value of specified type including enum</returns>
        public T GetValue<T>(IDataReader reader, int columnIndex)
        {
            // Check for DB NULL values
            if (reader.IsDBNull(columnIndex))
            {
                // If given type is String then return empty string as value
                // Otherwise return the default value of given type
                if (typeof(T) == typeof(string))
                {
                    object obj;
                    obj = string.Empty;
                    return (T)obj;
                }
                else
                {
                    return default(T);
                }
            }
           
            // If given type is Enum then convert the value to enum type otherwise cast it to desired type
            if (typeof(T).IsEnum)
            {
                return (T)Enum.ToObject(typeof(T), reader[columnIndex]);
            }
            else
            {
                return (T)reader[columnIndex];
            }
       }

4 comments:

  1. Thank you so much for the post... it is really very simple to use. keep posting...

    ReplyDelete
  2. Nice explanation. Code snippets were really helpful.

    ReplyDelete