Search code examples
c#genericspass-through

C# pass through generic as parameter


I have a method like that:

private Contact GetContactFromDbReaderWithSingleResult(DbDataReader dbReader)
{
    if (dbReader.HasRows)
    {
        return new DataReaderReflection().DataReaderToEntity<Contact>(dbReader)[0];
    }

    return null;
}

and then I could have a quite similar method like that:

private Email GetEmailFromDbReaderWithSingleResult(DbDataReader dbReader)
{
    if (dbReader.HasRows)
    {
        return new DataReaderReflection().DataReaderToEntity<Email>(dbReader)[0];
    }

    return null;
}

The signature of the DataReaderToEntity-Method is:

public List<T> DataReaderToEntity<T>(IDataReader dr) where T : new()

Now I want to create a generic variant GetGenericEntityFromDbReaderWithSingleResullt.

My approach looks like that, but it's not correct:

private object? GetEntityFromDbReaderWithSingleResult<T>(DbDataReader dbReader)
{
    if (dbReader.HasRows)
    {
        return new DataReaderReflection().DataReaderToEntity<typeof(T)>(dbReader)[0];
    }

    return null;
}

Still learning to deal with generics though... What am I doing wrong?

Thank in advance!


Solution

  • Change your return type to T instead of object and remove the typeof:

    private T GetEntityFromDbReaderWithSingleResult<T>(DbDataReader dbReader) where T : new()
    {
        if (dbReader.HasRows)
        {
            return new DataReaderReflection().DataReaderToEntity<T>(dbReader)[0];
        }
    
        return default(T);
    }