ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

Get

IDataReader extension to get values

Source

public static T Get<T>(this IDataReader rd, string column)
{
    return rd.Get(column, default(T));
}

public static T Get<T>(this IDataReader rd, string column, T defaultValue)
{
    try
    {
        int ordinal = rd.GetOrdinal(column);

        object value = rd[ordinal];

        if (rd.IsDBNull(ordinal))
        {
            value = defaultValue;
        }

        return (T)Convert.ChangeType(value, typeof(T));
        
    }
    catch (Exception e)
    {
        throw new DataReaderParseFieldException($"Erro na conversão de valores do atributo: [{column}] para tipo [{typeof(T)}]", e);
    }
}

Example

int id = reader.Get("Id", 10);
string nome = reader.Get("Nome", "...");
DateTime nascimento = reader.Get("Nascimento", DateTime.Now);
float valor = reader.Get("Valor", 0.05f);
decimal valorDecimal = reader.Get("Valor", new Decimal(15.75));

Author: Everton Thomas

Submitted on: 17 aug 2017

Language: C#

Type: System.Data.IDataReader

Views: 3826