IDataReader - GetValueTo

An IDataReader extension method that gets value to.

Try it

public static void Main()
{
	const string sql = @"SELECT 1 As IntColumn";
	
	using (var conn = new SqlConnection(FiddleHelper.GetConnectionStringSqlServer()))
    {
        conn.Open();
        using (DbCommand command = conn.CreateCommand())
        {
            command.CommandText = sql;
            using (IDataReader reader = command.ExecuteReader())
            {					
				while (reader.Read())
                {
					//C# Extension Method: IDataReader - GetValueTo
                    var result = reader.GetValueTo<int>("IntColumn");
					Console.WriteLine(result);
				}
            }
        }
    }
}

View Source
using System.Data;

public static partial class Extensions
{
    /// <summary>
    ///     An IDataReader extension method that gets value to.
    /// </summary>
    /// <typeparam name="T">Generic type parameter.</typeparam>
    /// <param name="this">The @this to act on.</param>
    /// <param name="index">Zero-based index of the.</param>
    /// <returns>The value to.</returns>
    public static T GetValueTo<T>(this IDataReader @this, int index)
    {
        return @this.GetValue(index).To<T>();
    }

    /// <summary>
    ///     An IDataReader extension method that gets value to.
    /// </summary>
    /// <typeparam name="T">Generic type parameter.</typeparam>
    /// <param name="this">The @this to act on.</param>
    /// <param name="columnName">Name of the column.</param>
    /// <returns>The value to.</returns>
    public static T GetValueTo<T>(this IDataReader @this, string columnName)
    {
        return @this.GetValue(@this.GetOrdinal(columnName)).To<T>();
    }
}